/* global React */
const { useState: useStateResume, useRef: useRefResume } = React;

// ─────────────────────────────────────────────────────────────
// RESUME REVIEW — AI-scored acting resume feedback
// Frontend posts to /api/review (Vercel serverless function).
// In the preview (no backend) the "sample review" button shows
// the results design with mock data.
// ─────────────────────────────────────────────────────────────

const RESUME_API = '/api/review';

const RESUME_CATEGORIES = [
  { key: 'presentation', label: 'Presentation & layout',        max: 20 },
  { key: 'headshot',     label: 'Headshot & personal details',  max: 15 },
  { key: 'training',     label: 'Training & education',         max: 20 },
  { key: 'experience',   label: 'Experience & credits',         max: 25 },
  { key: 'skills',       label: 'Skills & special abilities',   max: 10 },
  { key: 'compliance',   label: 'Industry standards compliance',max: 10 },
];

const RESUME_SAMPLE = {
  extractedName: 'Sample Performer',
  extractedEmail: 'performer@example.com',
  totalScore: 72,
  categories: {
    presentation: { score: 16, comment: 'Clean and well organised. Slightly long at three pages; tighten to two for agent submissions.' },
    headshot:     { score: 11, comment: 'Contact details present. Headshot reference noted but no agency contact listed.' },
    training:     { score: 15, comment: 'Strong training section with named institutions, though some dates are missing.' },
    experience:   { score: 18, comment: 'Good range of credits. Add director and production company columns for clarity.' },
    skills:       { score: 7,  comment: 'Solid special skills. Specify accent proficiency and dance styles to industry standard.' },
    compliance:   { score: 5,  comment: 'Remove the personal objective statement and order credits reverse-chronologically.' },
  },
  summary: 'A capable emerging resume that reads as a developing professional. With tighter formatting and clearer credit columns this would sit comfortably in front of casting directors for supporting and ensemble roles.',
  strengths: [
    'Clear, consistent typography that is easy to scan.',
    'Named training institutions lend credibility.',
    'Good breadth of stage and screen credits for the level.',
  ],
  growthAreas: [
    'Resume runs long; trim to two pages maximum.',
    'Credit entries lack director and production company detail.',
    'Personal objective statement is not industry standard.',
  ],
  recommendations: [
    'Reformat credits into Production / Role / Director columns.',
    'Remove the objective statement at the top.',
    'Add specific accent and dance proficiencies.',
    'List representation and contact in a consistent header.',
    'Reduce to two pages, leading with strongest credits.',
  ],
};

function fileToBase64Resume(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result.split(',')[1]);
    reader.onerror = () => reject(reader.error);
    reader.readAsDataURL(file);
  });
}

function guessTypeResume(name) {
  const ext = (name || '').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';
}

// ── Score ring ────────────────────────────────────────────────
const ScoreRing = ({ score }) => {
  const r = 84, c = 2 * Math.PI * r;
  const pct = Math.max(0, Math.min(100, score)) / 100;
  return (
    <div style={{ position: 'relative', width: 200, height: 200, flexShrink: 0 }}>
      <svg viewBox="0 0 200 200" style={{ width: '100%', height: '100%', transform: 'rotate(-90deg)' }}>
        <circle cx="100" cy="100" r={r} fill="none" stroke="var(--hairline-ink)" strokeWidth="2" />
        <circle cx="100" cy="100" r={r} fill="none" stroke="var(--spotlight)" strokeWidth="2"
          strokeDasharray={c} strokeDashoffset={c * (1 - pct)}
          style={{ transition: 'stroke-dashoffset 1.2s var(--ease-stage)' }} />
      </svg>
      <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
        <span style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 64, letterSpacing: '-0.03em', lineHeight: 1, color: 'var(--paper)' }}>{score}</span>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-on-ink-2)', letterSpacing: '0.08em' }}>/ 100</span>
      </div>
    </div>
  );
};

// ── Results ───────────────────────────────────────────────────
const ResumeResults = ({ data, onReset }) => {
  const cats = data.categories || {};
  const total = data.totalScore != null
    ? data.totalScore
    : RESUME_CATEGORIES.reduce((s, c) => s + (cats[c.key]?.score || 0), 0);

  const List = ({ items }) => (
    <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 12 }}>
      {(items || []).map((t, i) => (
        <li key={i} style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
          <span style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 14, color: 'var(--mid)', transform: 'skewX(-12deg)', marginTop: 2 }}>/</span>
          <span style={{ fontSize: 16, lineHeight: 1.55, color: 'var(--ink)' }}>{t}</span>
        </li>
      ))}
    </ul>
  );

  return (
    <div style={{ marginTop: 64 }}>
      {/* Score card — ink */}
      <div style={{ background: 'var(--ink)', color: 'var(--paper)', padding: '56px 48px', display: 'flex', alignItems: 'center', gap: 56, flexWrap: 'wrap' }}>
        <ScoreRing score={total} />
        <div style={{ flex: 1, minWidth: 260 }}>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-on-ink-2)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 12 }}>
            Your resume score
          </div>
          {data.extractedName && (
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 'clamp(32px, 4vw, 56px)', letterSpacing: '-0.025em', lineHeight: 1, marginBottom: 8 }}>
              {data.extractedName}
            </div>
          )}
          {data.extractedEmail && (
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--fg-on-ink-2)', letterSpacing: '0.04em' }}>
              {data.extractedEmail}
            </div>
          )}
        </div>
      </div>

      {/* Category breakdown */}
      <div style={{ padding: '56px 0' }}>
        <Eyebrow style={{ color: 'var(--mid)' }}>Category breakdown</Eyebrow>
        <div style={{ marginTop: 32, borderTop: '1px solid var(--hairline)' }}>
          {RESUME_CATEGORIES.map((c) => {
            const cat = cats[c.key] || { score: 0, comment: '' };
            const pct = Math.round((cat.score / c.max) * 100);
            return (
              <div key={c.key} style={{ padding: '24px 0', borderBottom: '1px solid var(--hairline)' }}>
                <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 16, marginBottom: 14 }}>
                  <span style={{ fontFamily: 'var(--font-sans)', fontSize: 18, fontWeight: 700, letterSpacing: '-0.01em' }}>{c.label}</span>
                  <span style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 22, letterSpacing: '-0.02em' }}>
                    {cat.score}<span style={{ color: 'var(--mid-soft)', fontSize: 15 }}>/{c.max}</span>
                  </span>
                </div>
                <div style={{ height: 4, background: 'var(--hairline)', position: 'relative', marginBottom: cat.comment ? 14 : 0 }}>
                  <div style={{ position: 'absolute', inset: 0, width: `${pct}%`, background: 'var(--ink)', transition: 'width 1s var(--ease-stage)' }} />
                </div>
                {cat.comment && (
                  <p style={{ fontSize: 15, lineHeight: 1.55, color: 'var(--mid)', margin: 0, maxWidth: '70ch' }}>{cat.comment}</p>
                )}
              </div>
            );
          })}
        </div>
      </div>

      {/* Overall read */}
      {data.summary && (
        <div style={{ padding: '0 0 56px' }}>
          <Eyebrow style={{ color: 'var(--mid)' }}>Overall read</Eyebrow>
          <p style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 'clamp(24px, 3vw, 36px)', letterSpacing: '-0.02em', lineHeight: 1.15, color: 'var(--ink)', margin: '24px 0 0', textWrap: 'balance', maxWidth: '40ch' }}>
            {data.summary}
          </p>
        </div>
      )}

      {/* Strengths / growth / recommendations */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 0, border: '1px solid var(--hairline)' }}>
        {[
          { h: 'Strengths', items: data.strengths },
          { h: 'Areas for growth', items: data.growthAreas },
          { h: 'Recommended next steps', items: data.recommendations },
        ].map((col, i) => (
          <div key={col.h} style={{ padding: '36px 32px', borderLeft: i === 0 ? '0' : '1px solid var(--hairline)' }}>
            <h4 style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 22, letterSpacing: '-0.01em', lineHeight: 1.1, margin: '0 0 24px' }}>{col.h}</h4>
            <List items={col.items} />
          </div>
        ))}
      </div>

      <div style={{ marginTop: 48, display: 'flex', gap: 16, alignItems: 'center', flexWrap: 'wrap' }}>
        <Button onClick={(e) => { e.preventDefault(); onReset(); }}>Review another resume</Button>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--mid)', letterSpacing: '0.02em', maxWidth: '52ch' }}>
          This is a free, automated guide — not a guarantee of representation. Our team will manually review your submission and follow up with real, human feedback. You do not need to be signed with CentreStage to use this tool.
        </span>
      </div>
    </div>
  );
};

// ── Screen ────────────────────────────────────────────────────
const ResumeScreen = ({ navigate }) => {
  const [file, setFile] = useStateResume(null);
  const [consent, setConsent] = useStateResume(false);
  const [name, setName] = useStateResume('');
  const [email, setEmail] = useStateResume('');
  const [status, setStatus] = useStateResume('idle'); // idle | loading | done | error
  const [result, setResult] = useStateResume(null);
  const [error, setError] = useStateResume(null);

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

  const reset = () => {
    setFile(null); setConsent(false); setName(''); setEmail('');
    setStatus('idle'); setResult(null); setError(null);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

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

    setStatus('loading');
    try {
      const base64 = await fileToBase64Resume(file.file || file);
      const res = await fetch(RESUME_API, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          filename: file.name,
          filetype: guessTypeResume(file.name),
          fileData: base64,
          name: name.trim(),
          email: email.trim(),
          nameOverride: name.trim(),
          emailOverride: email.trim(),
        }),
      });
      if (!res.ok) throw new Error('Server responded with ' + res.status);
      const data = await res.json();
      setResult(data);
      setStatus('done');
      window.scrollTo({ top: 0, behavior: 'smooth' });
    } catch (err) {
      console.error(err);
      setStatus('idle');
      setError('We could not reach the review engine. This tool activates once the site is deployed with the review service connected. In the meantime, use “See a sample review” below to preview your results.');
    }
  };

  const showSample = () => {
    setResult(RESUME_SAMPLE);
    setStatus('done');
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  if (status === 'done' && result) {
    return (
      <main data-screen-label="Resume Review · Results" 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 Review <Slash /> Results</Eyebrow>
          <div style={{ flex: 1, height: 1, background: 'var(--hairline)' }} />
        </div>
        <ResumeResults data={result} onReset={reset} />
      </main>
    );
  }

  return (
    <main data-screen-label="Resume Review">
      {/* 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)' }}>No sign-up required</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',
        }}>
          A free, honest read of<br/>your 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: '52ch' }}>
            A completely free resume feedback tool, open to every performer — you do not need to be signed with CentreStage to use it. Upload your resume and our review engine reads it the way an Australian agent or casting director would, scoring it out of one hundred across six industry categories with practical, growth-focused feedback you can act on this week.
          </p>
          <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', justifyContent: 'flex-end' }}>
            <Button href="#resume" onClick={(e) => { e.preventDefault(); document.getElementById('resume-upload')?.scrollIntoView({ behavior: 'smooth' }); }}>Upload resume · free</Button>
          </div>
        </div>
      </section>

      <Hairline />

      {/* How it works */}
      <section style={{ maxWidth: 1600, margin: '0 auto', padding: '120px 48px' }}>
        <SectionHeader eyebrow="The process" />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 0, border: '1px solid var(--hairline)' }}>
          {[
            { n: '01', t: 'Upload', d: 'Drop in your PDF or Word resume. We read your name and email automatically — nothing to retype.' },
            { n: '02', t: 'Analyse', d: 'The engine reviews your resume against six categories used by Australian agents and casting directors.' },
            { n: '03', t: 'Receive', d: 'Get a score out of one hundred, a category breakdown, written strengths, and clear next steps.' },
          ].map((s, i) => (
            <div key={s.n} style={{ padding: '48px 36px', borderLeft: i === 0 ? '0' : '1px solid var(--hairline)', display: 'flex', flexDirection: 'column', gap: 18 }}>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--mid)', letterSpacing: '0.08em' }}>{s.n} / 03</div>
              <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 36, letterSpacing: '-0.02em', lineHeight: 1, margin: 0 }}>{s.t}</h3>
              <p style={{ fontSize: 15, lineHeight: 1.6, color: 'var(--ink)', margin: 0 }}>{s.d}</p>
            </div>
          ))}
        </div>
      </section>

      {/* What we review — dark band */}
      <section style={{ background: 'var(--ink)', color: 'var(--paper)' }}>
        <div style={{ maxWidth: 1600, margin: '0 auto', padding: '120px 48px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 80, alignItems: 'flex-start' }}>
          <div>
            <Eyebrow style={{ color: 'var(--spotlight)' }}>What we review</Eyebrow>
            <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 'clamp(40px, 5.5vw, 88px)', letterSpacing: '-0.03em', lineHeight: 0.95, margin: '24px 0 24px', color: 'var(--paper)', textWrap: 'balance' }}>
              Six categories.<br/>One hundred points.
            </h2>
            <p style={{ fontSize: 17, lineHeight: 1.6, color: 'var(--fg-on-ink-2)', margin: 0, maxWidth: '44ch' }}>
              Assessed against the standards expected by Australian and international agents, casting directors and producers. Every score is backed by evidence and a clear path forward.
            </p>
          </div>
          <ul style={{ margin: 0, padding: 0, listStyle: 'none', borderTop: '1px solid var(--hairline-ink)' }}>
            {RESUME_CATEGORIES.map((c) => (
              <li key={c.key} style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 16, padding: '22px 0', borderBottom: '1px solid var(--hairline-ink)' }}>
                <span style={{ fontFamily: 'var(--font-sans)', fontSize: 18, fontWeight: 700, letterSpacing: '-0.01em', color: 'var(--paper)' }}>{c.label}</span>
                <span style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 28, letterSpacing: '-0.02em', color: 'var(--spotlight)' }}>{c.max}</span>
              </li>
            ))}
          </ul>
        </div>
      </section>

      {/* Upload */}
      <section id="resume-upload" style={{ maxWidth: 1100, margin: '0 auto', padding: '120px 48px' }}>
        <div style={{ marginBottom: 40 }}>
          <Eyebrow style={{ color: 'var(--mid)' }}>Upload your resume</Eyebrow>
          <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 'clamp(40px, 6vw, 88px)', letterSpacing: '-0.03em', lineHeight: 0.95, margin: '20px 0 0', textWrap: 'balance' }}>
            Ready when you are.
          </h2>
        </div>

        {/* How to read this feedback */}
        <div style={{ border: '1px solid var(--ink)', padding: '28px 32px', marginBottom: 48, display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--mid)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>
            How to read this feedback
          </div>
          <p style={{ fontSize: 16, lineHeight: 1.6, color: 'var(--ink)', margin: 0, maxWidth: '74ch' }}>
            This is an automated analysis. It does not replace genuine human judgement — instead it reviews the structure of your resume, identifies gaps, flags common red flags, and checks your presentation against the standards Australian agents and casting directors expect. Think of it as a fast, practical first pass.
          </p>
          <p style={{ fontSize: 16, lineHeight: 1.6, color: 'var(--ink)', margin: 0, maxWidth: '74ch' }}>
            After your resume is processed, our team manually reviews every submission and gets back to you with additional, real feedback from a person. The score is your starting point; the conversation that follows is where the real value is.
          </p>
        </div>

        {status === 'loading' ? (
          <div style={{ border: '1px solid var(--hairline)', padding: '80px 48px', textAlign: 'center' }}>
            <div style={{ display: 'inline-block', width: 40, height: 40, border: '2px solid var(--hairline)', borderTopColor: 'var(--ink)', borderRadius: '50%', animation: 'cs-slash-spin 0.9s linear infinite' }} />
            <p style={{ fontSize: 17, lineHeight: 1.55, color: 'var(--ink)', margin: '28px auto 0', maxWidth: '40ch' }}>
              Reading your resume against industry standards. This usually takes about thirty seconds.
            </p>
          </div>
        ) : (
          <form onSubmit={submit} noValidate style={{ display: 'flex', flexDirection: 'column', gap: 32 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 28 }}>
              <TextField label="Your name" name="resumeName" required placeholder="First and last name" autoComplete="name" value={name} onChange={setName} />
              <TextField label="Your email" name="resumeEmail" type="email" required placeholder="you@example.com" autoComplete="email" value={email} onChange={setEmail} />
            </div>
            <p style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--mid)', letterSpacing: '0.02em', lineHeight: 1.6, margin: 0, maxWidth: '70ch' }}>
              Your name and email are required so we can send your results and have our team follow up with real, human feedback. This tool is free and open to everyone — you do not need to be signed with CentreStage to use it. We never share your details with third parties.
            </p>

            <FileUpload
              label="Your resume" name="resume" required accept=".pdf,.doc,.docx"
              hint="PDF, DOC or DOCX · max 10 MB"
              value={file} onChange={setFile}
            />

            <div style={{ paddingTop: 8, borderTop: '1px solid var(--hairline)' }}>
              <ConsentCheckbox
                value={consent} onChange={setConsent}
                label={(
                  <span>
                    I consent to my resume being analysed by code for the purpose of providing feedback, and to CentreStage Agency contacting me about my results.{' '}
                    <span style={{ color: 'var(--mid)' }}>CentreStage Agency does not share submissions with third parties.</span>
                  </span>
                )}
              />
            </div>

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

            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 24, flexWrap: 'wrap' }}>
              <button type="button" onClick={showSample}
                style={{ background: 'transparent', border: 0, padding: 0, cursor: 'pointer', fontFamily: 'var(--font-sans)', fontSize: 12, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--mid)', textDecoration: 'underline', textUnderlineOffset: 4 }}>
                See a sample review →
              </button>
              <button type="submit" className="cs-btn"
                style={{ opacity: ready ? 1 : 0.4, pointerEvents: ready ? 'auto' : 'none' }}>
                Get my score <span style={{ marginLeft: 8 }}>→</span>
              </button>
            </div>
          </form>
        )}
      </section>
    </main>
  );
};

Object.assign(window, { ResumeScreen });
