const FORMSPREE_URL = 'https://formspree.io/f/mgorzzpq';

function CandidaturaModal({ job, onClose }) {
  const [status, setStatus] = React.useState('idle'); // idle | sending | done | error

  React.useEffect(() => {
    document.body.style.overflow = 'hidden';
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => { document.body.style.overflow = ''; window.removeEventListener('keydown', onKey); };
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setStatus('sending');
    const data = new FormData(e.target);
    data.append('vaga', job.t);
    data.append('departamento', job.dept);
    try {
      const res = await fetch(FORMSPREE_URL, {
        method: 'POST', body: data, headers: { Accept: 'application/json' }
      });
      setStatus(res.ok ? 'done' : 'error');
    } catch {
      setStatus('error');
    }
  };

  const inputStyle = {
    width: '100%', background: 'var(--bg)', border: '1px solid var(--line)',
    borderRadius: 10, padding: '12px 14px', color: 'var(--ink)', fontSize: 15,
    outline: 'none', boxSizing: 'border-box', fontFamily: 'inherit',
    transition: 'border-color 0.2s',
  };
  const labelStyle = { fontSize: 12, opacity: 0.6, letterSpacing: '0.06em', textTransform: 'uppercase', display: 'block', marginBottom: 6 };

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 9990, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '24px' }}
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.72)', backdropFilter: 'blur(4px)' }} onClick={onClose} />
      <div style={{ position: 'relative', zIndex: 1, background: 'var(--bg-2)', borderRadius: '24px',
        width: '100%', maxWidth: 760, maxHeight: '90vh', display: 'flex', flexDirection: 'column',
        border: '1px solid var(--line)' }}>

        {/* Header */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start',
          padding: '28px 36px 20px', borderBottom: '1px solid var(--line)', flexShrink: 0 }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 6 }}>Candidatura</div>
            <h2 className="display" style={{ fontSize: 'clamp(20px,2.5vw,28px)', margin: 0, lineHeight: 1.15 }}>{job.t}</h2>
            <div style={{ display: 'flex', gap: 10, marginTop: 8, flexWrap: 'wrap' }}>
              <span className="chip">{job.dept}</span>
              <span style={{ fontSize: 13, opacity: 0.55 }}>{job.loc} · {job.type}</span>
            </div>
          </div>
          <button onClick={onClose} style={{ background: 'var(--bg-3)', border: '1px solid var(--line)',
            borderRadius: '50%', width: 34, height: 34, cursor: 'pointer', color: 'var(--ink)',
            fontSize: 18, display: 'grid', placeItems: 'center', flexShrink: 0, marginTop: 4 }}>×</button>
        </div>

        {/* Body */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '28px 36px 36px' }}>
          {status === 'done' ? (
            <div style={{ textAlign: 'center', padding: '48px 0' }}>
              <div style={{ fontSize: 48, marginBottom: 16 }}>✓</div>
              <h3 className="display" style={{ fontSize: 28, marginBottom: 12 }}>Candidatura enviada!</h3>
              <p style={{ opacity: 0.7, fontSize: 15 }}>Obrigado pelo interesse. Entraremos em contato em breve.</p>
              <button onClick={onClose} style={{ marginTop: 32, padding: '12px 28px', background: 'var(--crimson)',
                color: '#fff', border: 'none', borderRadius: 10, fontSize: 15, cursor: 'pointer', fontWeight: 600 }}>Fechar</button>
            </div>
          ) : (
            <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
              <div className="cand-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                <div>
                  <label style={labelStyle}>Nome completo *</label>
                  <input name="nome" required style={inputStyle} placeholder="Seu nome" />
                </div>
                <div>
                  <label style={labelStyle}>E-mail *</label>
                  <input name="email" type="email" required style={inputStyle} placeholder="seu@email.com" />
                </div>
              </div>
              <div className="cand-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                <div>
                  <label style={labelStyle}>LinkedIn</label>
                  <input name="linkedin" style={inputStyle} placeholder="linkedin.com/in/..." />
                </div>
                <div>
                  <label style={labelStyle}>Portfólio / GitHub</label>
                  <input name="portfolio" style={inputStyle} placeholder="github.com/..." />
                </div>
              </div>
              <div>
                <label style={labelStyle}>Por que a Atom Forge? *</label>
                <textarea name="mensagem" required rows={4} style={{ ...inputStyle, resize: 'vertical' }}
                  placeholder="Conte um pouco sobre você e por que essa vaga faz sentido pra você..." />
              </div>
              {status === 'error' && (
                <p style={{ color: 'var(--crimson)', fontSize: 13, margin: 0 }}>Algo deu errado. Tente novamente ou envie por e-mail.</p>
              )}
              <button type="submit" disabled={status === 'sending'} style={{
                padding: '14px 28px', background: 'var(--crimson)', color: '#fff', border: 'none',
                borderRadius: 10, fontSize: 15, cursor: status === 'sending' ? 'wait' : 'pointer',
                fontWeight: 600, opacity: status === 'sending' ? 0.7 : 1, alignSelf: 'flex-end',
              }}>
                {status === 'sending' ? 'Enviando…' : 'Enviar candidatura'}
              </button>
            </form>
          )}
        </div>
      </div>
    </div>
  );
}

// Careers page — scaled-down, honest. Adds personas with photos.
function PageCarreiras({ setPage }) {
  useReveal();
  const t = useT();
  const [dept, setDept] = React.useState('Todos');
  const [selectedJob, setSelectedJob] = React.useState(null);

  const jobs = [
    { t: 'Engenheiro(a) de Software Júnior — Go', dept: 'Engenharia', loc: 'Remoto BR', type: 'PJ' },
    { t: 'Engenheiro(a) de Software Pleno — TypeScript', dept: 'Engenharia', loc: 'Remoto BR', type: 'PJ' },
    { t: 'ML Engineer Júnior — IA Aplicada', dept: 'IA & Dados', loc: 'Remoto BR', type: 'PJ' },
    { t: 'Product Designer Júnior', dept: 'Design', loc: 'Remoto BR', type: 'PJ' },
  ];

  const depts = ['Todos', 'Engenharia', 'IA & Dados', 'Design'];
  const deptLabel = (d) => d === 'Todos' ? t('c.filter_all') : d;
  const visible = dept === 'Todos' ? jobs : jobs.filter(j => j.dept === dept);

  const personas = [
    {
      img: 'assets/persona-1.png',
      name: 'Pedro',
      role: 'Software Engineer · 3 anos na casa',
      quote: 'Vim de uma consultoria gigante esperando achar outra consultoria. Achei um estúdio. A diferença é que aqui eu conheço o nome de todo mundo — e o repositório cabe na minha cabeça.',
      tag: 'Engenharia',
    },
    {
      img: 'assets/persona-2.png',
      name: 'Larissa',
      role: 'Product Designer · 2 anos na casa',
      quote: 'Design aqui não é entregável — é decisão. Eu não mando o Figma pra ninguém implementar. Eu entro no PR, componente por componente, até o pixel ficar certo.',
      tag: 'Design',
    },
    {
      img: 'uploads/team-felipe.png',
      name: 'Felipe',
      role: 'Tech Lead · Fundador',
      quote: 'Saí do previsível pra fundar a Atom Forge. Queria construir com mais intenção, menos ruído e um time forte e bem alinhado, capaz de entregar com consistência. Todo dia. Sempre.',
      tag: 'Fundação',
    },
  ];

  return (
    <>
      <section style={{ padding: '80px 0 60px', position: 'relative', overflow: 'hidden' }}>
        <div className="tick-grid" />
        <div className="orb" style={{ width: 480, height: 480, background: 'var(--crimson)', top: -100, right: -100, opacity: 0.4 }} />
        <div className="shell" style={{ position: 'relative' }}>
          <Eyebrow>{t('ca.ey')}</Eyebrow>
          <h1 className="display" style={{ fontSize: 'clamp(44px, 9vw, 132px)', margin: '24px 0', maxWidth: '14ch', lineHeight: 0.96 }}>
            {t('ca.h1a')}{' '}
            <em className="display-italic" style={{ color: 'var(--crimson)' }}>{t('ca.h1em')}</em>
          </h1>
          <div style={{ display: 'flex', gap: 40, alignItems: 'flex-end', justifyContent: 'space-between', flexWrap: 'wrap' }}>
            <p style={{ fontSize: 19, maxWidth: 560, opacity: 0.78, lineHeight: 1.55, margin: 0 }}>
              {t('ca.sub')}
            </p>
            <Btn onClick={() => setPage('contato')}>{t('c.see_jobs')}</Btn>
          </div>
        </div>
      </section>

      <div className="divider" />

      {/* Values */}
      <section className="section-pad-sm">
        <div className="shell">
          <SectionHeader
            eyebrow={t('ca.val_ey')}
            title={<>{t('ca.val_h2a')} <em className="display-italic">{t('ca.val_h2em')}</em></>}
          />
          <div className="grid grid-3 val-grid" style={{ marginTop: 56 }}>
            {[
              { n: '01', t: t('ca.v1t'), d: t('ca.v1d') },
              { n: '02', t: t('ca.v2t'), d: t('ca.v2d') },
              { n: '03', t: t('ca.v3t'), d: t('ca.v3d') },
              { n: '04', t: t('ca.v4t'), d: t('ca.v4d') },
              { n: '05', t: t('ca.v5t'), d: t('ca.v5d') },
            ].map((v, i) => (
              <Reveal key={v.n} delay={i * 60}>
                <div style={{ padding: '28px 0', borderTop: '1px solid var(--line)' }}>
                  <div className="eyebrow" style={{ marginBottom: 14 }}>{v.n}</div>
                  <h3 className="display" style={{ fontSize: 'clamp(22px, 2.4vw, 28px)', margin: '0 0 10px', lineHeight: 1.15 }}>{v.t}</h3>
                  <p style={{ opacity: 0.72, fontSize: 14.5, lineHeight: 1.55, margin: 0 }}>{v.d}</p>
                </div>
              </Reveal>
            ))}
          </div>
        </div>
      </section>

      {/* PERSONAS — quem trabalha aqui */}
      <section className="section-pad" style={{ background: 'var(--bg-2)' }}>
        <div className="shell">
          <SectionHeader
            eyebrow={t('ca.team_ey')}
            title={<>{t('ca.team_h2a')} <em className="display-italic">{t('ca.team_h2em')}</em></>}
            subtitle={t('ca.team_sub')}
          />
          <div className="persona-grid" style={{ marginTop: 64, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24 }}>
            {personas.map((p, i) => (
              <Reveal key={p.name} delay={i * 90}>
                <article className="persona-card" style={{
                  borderRadius: 20,
                  overflow: 'hidden',
                  border: '1px solid var(--line)',
                  background: 'var(--bg)',
                  display: 'flex', flexDirection: 'column',
                  height: '100%',
                  transition: 'transform 0.3s ease, border-color 0.3s',
                }}>
                  <div style={{
                    aspectRatio: '4 / 3',
                    background: 'var(--bg-3)',
                    position: 'relative',
                    overflow: 'hidden',
                  }}>
                    <img src={p.img} alt={p.name} style={{
                      width: '100%', height: '100%', objectFit: 'cover',
                      display: 'block',
                    }} />
                    <div style={{
                      position: 'absolute', top: 16, left: 16,
                      padding: '5px 11px', borderRadius: 999,
                      background: 'color-mix(in srgb, var(--bg) 85%, transparent)',
                      backdropFilter: 'blur(6px)',
                      fontFamily: 'var(--mono)', fontSize: 10,
                      letterSpacing: '0.12em', textTransform: 'uppercase',
                      color: 'var(--ink)',
                    }}>{p.tag}</div>
                  </div>
                  <div style={{ padding: '24px 24px 28px', display: 'flex', flexDirection: 'column', flex: 1 }}>
                    <div className="display" style={{ fontSize: 22, lineHeight: 1.1 }}>{p.name}</div>
                    <div className="eyebrow" style={{ marginTop: 4, fontSize: 10, opacity: 0.7 }}>{p.role}</div>
                    <div style={{
                      fontFamily: 'var(--serif)',
                      fontSize: 16,
                      lineHeight: 1.55,
                      fontStyle: 'italic',
                      marginTop: 20,
                      paddingTop: 20,
                      borderTop: '1px solid var(--line)',
                      color: 'var(--ink)',
                      opacity: 0.85,
                      flex: 1,
                      textWrap: 'pretty',
                    }}>
                      <span style={{ color: 'var(--crimson)', fontSize: 28, lineHeight: 0, verticalAlign: '-0.4em', marginRight: 4, fontFamily: 'var(--serif)' }}>“</span>
                      {p.quote}
                    </div>
                  </div>
                </article>
              </Reveal>
            ))}
          </div>
        </div>
      </section>

      {/* Jobs */}
      <section className="section-pad">
        <div className="shell">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 32, flexWrap: 'wrap', gap: 24 }}>
            <SectionHeader eyebrow={`${jobs.length} ${t('c.see_jobs')}`} title={<>{t('ca.jobs_h2a')} <em className="display-italic">{t('ca.jobs_h2em')}</em></>} />
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {depts.map(d => (
                <button key={d} onClick={() => setDept(d)} style={{
                  padding: '8px 14px',
                  borderRadius: 999,
                  fontSize: 13,
                  background: dept === d ? 'var(--ink)' : 'transparent',
                  color: dept === d ? 'var(--bg)' : 'var(--ink)',
                  border: dept === d ? 'none' : '1px solid var(--line)',
                  transition: 'all 0.2s',
                  fontWeight: dept === d ? 600 : 400,
                }}>{deptLabel(d)}</button>
              ))}
            </div>
          </div>

          <div>
            {visible.map((j, i) => (
              <Reveal key={j.t} delay={i * 30}>
                <a href="#" onClick={(e) => { e.preventDefault(); setSelectedJob(j); }}
                   style={{
                     display: 'grid',
                     gridTemplateColumns: '2fr 1fr 1fr 1fr auto',
                     alignItems: 'center',
                     gap: 24,
                     padding: '24px 0',
                     borderTop: '1px solid var(--line)',
                     borderBottom: i === visible.length - 1 ? '1px solid var(--line)' : 'none',
                     transition: 'padding 0.2s',
                   }}
                   className="job-row"
                   onMouseEnter={(e) => e.currentTarget.style.paddingLeft = '12px'}
                   onMouseLeave={(e) => e.currentTarget.style.paddingLeft = '0'}
                >
                  <div className="display" style={{ fontSize: 'clamp(18px, 2vw, 24px)', lineHeight: 1.15 }}>{j.t}</div>
                  <Chip>{j.dept}</Chip>
                  <div style={{ fontSize: 14, opacity: 0.7 }}>{j.loc}</div>
                  <div style={{ fontFamily: 'var(--mono)', fontSize: 12, opacity: 0.6 }}>{j.type}</div>
                  <ArrowIcon size={18} />
                </a>
              </Reveal>
            ))}
          </div>
        </div>
      </section>

      {/* Life at the studio — scaled down, no inflated numbers */}
      <section className="section-pad" style={{ background: 'var(--bg-2)' }}>
        <div className="shell">
          <SectionHeader eyebrow={t('ca.life_ey')} title={<>{t('ca.life_h2a')} <em className="display-italic">{t('ca.life_h2em')}</em></>} />
          <div className="grid grid-3 daily-grid" style={{ marginTop: 56 }}>
            {[
              { k: t('ca.l1k'), t: t('ca.l1t'), d: t('ca.l1d') },
              { k: t('ca.l2k'), t: t('ca.l2t'), d: t('ca.l2d') },
              { k: t('ca.l3k'), t: t('ca.l3t'), d: t('ca.l3d') },
              { k: t('ca.l4k'), t: t('ca.l4t'), d: t('ca.l4d') },
              { k: t('ca.l5k'), t: t('ca.l5t'), d: t('ca.l5d') },
              { k: t('ca.l6k'), t: t('ca.l6t'), d: t('ca.l6d') },
            ].map((p, i) => (
              <Reveal key={p.k} delay={i * 60}>
                <div style={{
                  padding: 28,
                  background: 'var(--bg)',
                  borderRadius: 18,
                  height: '100%',
                  border: '1px solid var(--line)',
                  display: 'flex', flexDirection: 'column',
                  minHeight: 200,
                }}>
                  <div className="eyebrow" style={{ color: 'var(--crimson)' }}>{p.k}</div>
                  <div className="display" style={{ fontSize: 'clamp(20px, 2.2vw, 24px)', margin: '14px 0 10px', lineHeight: 1.15 }}>{p.t}</div>
                  <div style={{ fontSize: 14, opacity: 0.72, lineHeight: 1.55, flex: 1 }}>{p.d}</div>
                </div>
              </Reveal>
            ))}
          </div>
        </div>
      </section>

      <style>{`
        @media (max-width: 980px) {
          .persona-grid { grid-template-columns: 1fr !important; }
          .val-grid, .daily-grid { grid-template-columns: repeat(2, 1fr) !important; }
          .job-row { grid-template-columns: 1fr auto !important; gap: 8px !important; }
          .job-row > :nth-child(2), .job-row > :nth-child(3), .job-row > :nth-child(4) { display: none; }
        }
        @media (max-width: 640px) {
          .val-grid, .daily-grid { grid-template-columns: 1fr !important; }
          .cand-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>

      {selectedJob && <CandidaturaModal job={selectedJob} onClose={() => setSelectedJob(null)} />}
    </>
  );
}

Object.assign(window, { PageCarreiras });
