// associates.jsx — Página dedicada do Programa de Associados.
// Acessada via hash route #associados (PT) ou #associates (EN).
// Mantém header e footer; substitui o miolo da home.
//
// Contém:
//   - Contextualização editorial (o que é o programa, perfil esperado)
//   - Formulário (nome, e-mail, telefone, LinkedIn, currículo em anexo)
//   - Envio via FormSubmit com upload de arquivo via iframe hidden target
//     (para preservar o estado da SPA, sem navegar para fora)
//
// Endpoint: rafael@souzanunesecia.com.br
// Limite de arquivo: 5 MB (limite gratuito do FormSubmit).
// Tipos aceitos: PDF, DOC, DOCX.

const { useState: useStateAs, useRef: useRefAs } = React;

const ASSOCIATES_FORMSUBMIT = 'https://formsubmit.co/rafael@souzanunesecia.com.br';
const ASSOCIATES_IFRAME_NAME = 'associates-submit-target';
const MAX_CV_BYTES = 5 * 1024 * 1024; // 5 MB
const ACCEPTED_CV_EXT = ['.pdf', '.doc', '.docx'];

const AssociatesPage = () => {
  const { lang } = useLang();
  const formRef = useRefAs(null);
  const fileRef = useRefAs(null);
  const iframeRef = useRefAs(null);
  // Track whether the iframe load was triggered by an actual submission
  // (true) or just by the initial mount of the iframe element (false).
  const submittingRef = useRefAs(false);

  const [status, setStatus] = useStateAs('idle'); // idle | sending | success | error
  const [errorMsg, setErrorMsg] = useStateAs('');
  const [fileName, setFileName] = useStateAs('');

  const T = lang === 'pt' ? {
    eyebrow: 'Programa de Associados',
    pageTitle: (<>Trabalhar <em>conosco</em>.</>),
    intro: 'O Programa de Associados é a porta de entrada para profissionais que desejam construir ofício na casa. Não recrutamos por escala. Recrutamos por aderência: capacidade analítica acima da média, disposição para diagnóstico em profundidade, repertório técnico sólido em finanças corporativas, contabilidade, estratégia ou direito societário. Antes do mais: caráter compatível com uma prática em que cada parecer carrega assinatura pessoal.',
    contextHeading: 'Sobre o programa',
    context: [
      'Associados na Souza Nunes & Cia trabalham diretamente com os sócios fundadores em engajamentos de diagnóstico, reestruturação, valuation, governança e M&A no middle market brasileiro. Não há quadro júnior delegado a tarefas mecânicas: a casa opera com equipes enxutas em que cada profissional responde, com nome próprio, pelo material que produz.',
      'O ingresso pressupõe formação consolidada em uma das três frentes do tripé (Fayol, Porter, Damodaran) e disposição para aprofundá-la. Não buscamos generalistas reciclados. Buscamos especialistas em formação contínua, dispostos a ler balanço com a mesma seriedade com que leem o setor do cliente.',
      'O processo seletivo é direto: avaliamos currículo, perfil no LinkedIn, e, quando há aderência, conduzimos duas entrevistas técnicas conduzidas pelos próprios sócios. Não há prova de inglês, não há dinâmica de grupo, não há teste de personalidade. Há conversa sobre o seu repertório e sobre o que esperamos que você construa aqui.'
    ],
    formTitle: 'Candidatura',
    formIntro: 'Preencha os campos abaixo e anexe seu currículo (PDF, DOC ou DOCX, até 5 MB). Responderemos em até 5 dias úteis se houver aderência inicial ao perfil.',
    labelName: 'Nome completo',
    labelEmail: 'E-mail profissional',
    labelPhone: 'Telefone (com DDD)',
    labelLinkedIn: 'Perfil no LinkedIn',
    labelMessage: 'Mensagem (opcional)',
    labelCV: 'Currículo (PDF, DOC, DOCX, até 5 MB)',
    placeholderName: 'Como gostaria de ser chamado',
    placeholderEmail: 'seu@dominio.com.br',
    placeholderPhone: '(00) 00000-0000',
    placeholderLinkedIn: 'https://www.linkedin.com/in/seu-perfil',
    placeholderMessage: 'Conte brevemente o que o motiva a candidatar-se. Opcional.',
    chooseFile: 'Escolher arquivo',
    noFile: 'Nenhum arquivo selecionado',
    submit: 'Enviar candidatura',
    sending: 'Enviando…',
    success: 'Candidatura recebida. Avaliaremos seu material e retornaremos em até 5 dias úteis.',
    errorSize: 'Arquivo acima de 5 MB. Reduza o tamanho ou comprima o documento.',
    errorType: 'Formato não aceito. Use PDF, DOC ou DOCX.',
    errorGeneric: 'Não foi possível enviar agora. Tente novamente em instantes ou escreva diretamente para rafael@souzanunesecia.com.br.',
    backHome: 'Voltar ao início',
    privacy: 'Os dados informados são tratados em conformidade com a LGPD e usados exclusivamente para a avaliação desta candidatura.'
  } : {
    eyebrow: 'Associate Program',
    pageTitle: (<>Work <em>with us</em>.</>),
    intro: 'The Associate Program is the gateway for professionals who want to build craft inside the firm. We do not recruit by scale. We recruit by fit: above-average analytical capacity, disposition for in-depth diagnosis, solid technical repertoire in corporate finance, accounting, strategy or corporate law. Above all: character compatible with a practice in which every opinion carries personal signature.',
    contextHeading: 'About the program',
    context: [
      'Associates at Souza Nunes & Cia work directly with the founding partners on engagements involving diagnosis, restructuring, valuation, governance and M&A within the Brazilian middle market. There is no junior staff delegated to mechanical tasks: the firm operates with lean teams in which each professional is personally accountable for the material they produce.',
      'Joining presupposes consolidated training in one of the three sides of our tripod (Fayol, Porter, Damodaran) and a disposition to deepen it. We do not seek recycled generalists. We seek specialists in continuous formation, willing to read a balance sheet with the same seriousness they read the client’s sector.',
      'The selection process is direct: we review the CV, LinkedIn profile, and, when there is fit, we conduct two technical interviews led by the partners themselves. No English test, no group dynamics, no personality assessment. Just a conversation about your repertoire and what we expect you to build here.'
    ],
    formTitle: 'Application',
    formIntro: 'Fill in the fields below and attach your CV (PDF, DOC or DOCX, up to 5 MB). We will reply within 5 business days if there is initial fit with the profile.',
    labelName: 'Full name',
    labelEmail: 'Professional e-mail',
    labelPhone: 'Phone (with country/area code)',
    labelLinkedIn: 'LinkedIn profile',
    labelMessage: 'Message (optional)',
    labelCV: 'CV (PDF, DOC, DOCX, up to 5 MB)',
    placeholderName: 'How you’d like to be addressed',
    placeholderEmail: 'you@domain.com',
    placeholderPhone: '+00 00 00000-0000',
    placeholderLinkedIn: 'https://www.linkedin.com/in/your-profile',
    placeholderMessage: 'Briefly share what motivates your application. Optional.',
    chooseFile: 'Choose file',
    noFile: 'No file selected',
    submit: 'Submit application',
    sending: 'Sending…',
    success: 'Application received. We’ll review your materials and respond within 5 business days.',
    errorSize: 'File larger than 5 MB. Please reduce or compress the document.',
    errorType: 'Format not accepted. Use PDF, DOC or DOCX.',
    errorGeneric: 'Could not send right now. Please try again shortly or write directly to rafael@souzanunesecia.com.br.',
    backHome: 'Back to home',
    privacy: 'Data submitted is handled under LGPD and used exclusively to evaluate this application.'
  };

  const goBack = (e) => { e.preventDefault(); window.location.hash = ''; };

  const onFileChange = (e) => {
    const f = e.target.files && e.target.files[0];
    if (!f) {
      setFileName('');
      return;
    }
    const ext = '.' + (f.name.split('.').pop() || '').toLowerCase();
    if (!ACCEPTED_CV_EXT.includes(ext)) {
      setStatus('error');
      setErrorMsg(T.errorType);
      e.target.value = '';
      setFileName('');
      return;
    }
    if (f.size > MAX_CV_BYTES) {
      setStatus('error');
      setErrorMsg(T.errorSize);
      e.target.value = '';
      setFileName('');
      return;
    }
    setStatus('idle');
    setErrorMsg('');
    setFileName(f.name);
  };

  const handleSubmit = (e) => {
    // Pre-flight validation (file is required)
    const f = fileRef.current && fileRef.current.files && fileRef.current.files[0];
    if (!f) {
      e.preventDefault();
      setStatus('error');
      setErrorMsg(T.errorType);
      return;
    }
    setStatus('sending');
    setErrorMsg('');
    // Mark the next iframe load as a real submission completion
    submittingRef.current = true;
    // Let the browser submit the form to the hidden iframe naturally.
    // (We don't preventDefault here.)
  };

  const handleIframeLoad = () => {
    // The hidden iframe also fires "load" once on mount with about:blank.
    // Only react to loads that follow an actual submission.
    if (!submittingRef.current) return;
    submittingRef.current = false;
    setStatus('success');
    if (formRef.current) formRef.current.reset();
    setFileName('');
    // Scroll to the form so the success message is visible
    setTimeout(() => {
      const el = document.getElementById('associates-form');
      if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }, 100);
  };

  const sending = status === 'sending';
  const success = status === 'success';
  const error = status === 'error';

  return (
    <section className="associates-page" id="associates-page">
      <a href="#" className="partners-back" onClick={goBack}>
        <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
          <path d="M11 12 L5 8 L11 4"/>
        </svg>
        <span>{T.backHome}</span>
      </a>

      {/* Page intro */}
      <div className="associates-intro">
        <Reveal><div className="eyebrow">{T.eyebrow}</div></Reveal>
        <Reveal delay={1}><h1 className="partners-page-title">{T.pageTitle}</h1></Reveal>
        <Reveal delay={2}><p className="partners-page-intro">{T.intro}</p></Reveal>
      </div>

      {/* Contextualization */}
      <div className="associates-context">
        <Reveal><h2 className="associates-context-heading">{T.contextHeading}</h2></Reveal>
        {T.context.map((p, i) => (
          <Reveal key={i} delay={Math.min(i+1, 3)}>
            <p className="associates-context-p">{p}</p>
          </Reveal>
        ))}
      </div>

      {/* Form */}
      <div className="associates-form-wrap" id="associates-form">
        <Reveal><h2 className="associates-form-title">{T.formTitle}</h2></Reveal>
        <Reveal delay={1}><p className="associates-form-intro">{T.formIntro}</p></Reveal>

        {/* Hidden iframe: serves as the form's submission target so the page
            stays mounted (no navigation away from the SPA). */}
        <iframe
          ref={iframeRef}
          name={ASSOCIATES_IFRAME_NAME}
          title="associates form target"
          className="associates-iframe-hidden"
          aria-hidden="true"
          onLoad={handleIframeLoad}
        />

        <form
          ref={formRef}
          className="associates-form"
          action={ASSOCIATES_FORMSUBMIT}
          method="POST"
          encType="multipart/form-data"
          target={ASSOCIATES_IFRAME_NAME}
          onSubmit={handleSubmit}
        >
          {/* FormSubmit configuration fields */}
          <input type="hidden" name="_subject" value={lang === 'pt'
            ? 'Programa de Associados — Nova candidatura'
            : 'Associate Program — New application'}/>
          <input type="hidden" name="_template" value="table"/>
          <input type="hidden" name="_captcha" value="false"/>
          {/* Honeypot for spam */}
          <input type="text" name="_honey" tabIndex="-1" autoComplete="off"
                 style={{display:'none'}} aria-hidden="true"/>

          <div className="associates-grid">
            <div className="associates-field">
              <label htmlFor="associates-name">{T.labelName}<span className="req">*</span></label>
              <input id="associates-name" name="nome" type="text" required
                     placeholder={T.placeholderName}
                     autoComplete="name"/>
            </div>
            <div className="associates-field">
              <label htmlFor="associates-email">{T.labelEmail}<span className="req">*</span></label>
              <input id="associates-email" name="email" type="email" required
                     placeholder={T.placeholderEmail}
                     autoComplete="email"/>
            </div>
            <div className="associates-field">
              <label htmlFor="associates-phone">{T.labelPhone}<span className="req">*</span></label>
              <input id="associates-phone" name="telefone" type="tel" required
                     placeholder={T.placeholderPhone}
                     autoComplete="tel"/>
            </div>
            <div className="associates-field">
              <label htmlFor="associates-linkedin">{T.labelLinkedIn}<span className="req">*</span></label>
              <input id="associates-linkedin" name="linkedin" type="url" required
                     placeholder={T.placeholderLinkedIn}
                     pattern="https?://.+"/>
            </div>
          </div>

          <div className="associates-field associates-field-full">
            <label htmlFor="associates-message">{T.labelMessage}</label>
            <textarea id="associates-message" name="mensagem" rows="4"
                      placeholder={T.placeholderMessage}></textarea>
          </div>

          <div className="associates-field associates-field-full">
            <label htmlFor="associates-cv">{T.labelCV}<span className="req">*</span></label>
            <div className="associates-file-wrap">
              <label htmlFor="associates-cv" className="associates-file-btn">
                <svg width="14" height="14" viewBox="0 0 16 16" fill="none"
                     stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"
                     strokeLinejoin="round" aria-hidden="true">
                  <path d="M8 2 L8 11 M4 6 L8 2 L12 6 M2 13 L14 13"/>
                </svg>
                <span>{T.chooseFile}</span>
              </label>
              <span className="associates-file-name">{fileName || T.noFile}</span>
              <input
                id="associates-cv"
                ref={fileRef}
                name="curriculo"
                type="file"
                required
                accept=".pdf,.doc,.docx,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                onChange={onFileChange}
                className="associates-file-input"
              />
            </div>
          </div>

          {error && (
            <p className="associates-msg associates-msg-error" role="alert">{errorMsg || T.errorGeneric}</p>
          )}
          {success && (
            <p className="associates-msg associates-msg-success" role="status">{T.success}</p>
          )}

          <div className="associates-actions">
            <button type="submit" className="cta-btn" disabled={sending}>
              {sending ? T.sending : T.submit}
              {!sending && <ArrowIcon/>}
            </button>
            <p className="associates-privacy">{T.privacy}</p>
          </div>

          {/* Live region for screen readers */}
          <div className="visually-hidden" aria-live="polite" aria-atomic="true">
            {sending ? T.sending : success ? T.success : error ? (errorMsg || T.errorGeneric) : ''}
          </div>
        </form>
      </div>
    </section>
  );
};

window.AssociatesPage = AssociatesPage;
