// Clube da Luz — sections part C: Aplicação form (com validação inline) + Footer

const { useState: useStateC, useRef: useRefC, useEffect: useEffectC } = React;

const EMAIL_RE = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;

const VALIDATORS = {
  nome: (v) => {
    if (!v || !v.trim()) return "Diga como prefere ser chamado(a).";
    if (v.trim().length < 2) return "Pelo menos 2 letras, por favor.";
    return null;
  },
  email: (v) => {
    if (!v || !v.trim()) return "Precisamos de um e-mail para responder.";
    if (!EMAIL_RE.test(v.trim())) return "Esse e-mail parece incompleto.";
    return null;
  },
  oficio: (v) => {
    if (!v || v.trim().length < 3) return "Em poucas palavras: como você se apresenta.";
    return null;
  },
  intencao: (v) => {
    if (!v || v.trim().length < 40) return `Conte um pouco mais — ainda faltam ${Math.max(0, 40 - (v?.trim().length || 0))} caracteres.`;
    return null;
  },
  momento: (v) => {
    if (!v) return "Selecione o momento que mais se aproxima.";
    return null;
  },
};

/* ============================================================ */
/* Aplicação form                                                */
/* ============================================================ */
function Aplicacao() {
  const [step, setStep] = useStateC(0);
  const [form, setForm] = useStateC({
    nome: "", email: "", oficio: "", intencao: "", momento: "",
  });
  const [errors, setErrors] = useStateC({});
  const [touched, setTouched] = useStateC({});
  const [shakeKey, setShakeKey] = useStateC({});
  const [submitting, setSubmitting] = useStateC(false);
  const [submitted, setSubmitted] = useStateC(false);

  const validateField = (k, v) => {
    const err = VALIDATORS[k] ? VALIDATORS[k](v) : null;
    setErrors(e => ({ ...e, [k]: err }));
    return err;
  };

  const update = (k, v) => {
    setForm(f => ({ ...f, [k]: v }));
    if (touched[k]) validateField(k, v);
  };

  const blur = (k) => {
    setTouched(t => ({ ...t, [k]: true }));
    validateField(k, form[k]);
  };

  const stepFields = [
    ["nome", "email", "oficio"],
    ["intencao"],
    ["momento"],
  ];

  const stepIsValid = (i) => {
    const fields = stepFields[i];
    return fields.every(f => {
      const err = VALIDATORS[f] ? VALIDATORS[f](form[f]) : null;
      return !err;
    });
  };

  const tryAdvance = () => {
    const fields = stepFields[step];
    let firstErrorField = null;
    const newTouched = { ...touched };
    const newShakes = { ...shakeKey };
    fields.forEach(f => {
      const err = validateField(f, form[f]);
      newTouched[f] = true;
      if (err && !firstErrorField) firstErrorField = f;
      if (err) newShakes[f] = (newShakes[f] || 0) + 1;
    });
    setTouched(newTouched);
    setShakeKey(newShakes);
    if (firstErrorField) {
      // focus first error
      const el = document.querySelector(`[data-field="${firstErrorField}"]`);
      if (el && el.focus) setTimeout(() => el.focus(), 50);
      return;
    }
    setStep(s => s + 1);
  };

  const trySubmit = () => {
    const fields = stepFields[step];
    let firstErrorField = null;
    const newTouched = { ...touched };
    const newShakes = { ...shakeKey };
    fields.forEach(f => {
      const err = validateField(f, form[f]);
      newTouched[f] = true;
      if (err && !firstErrorField) firstErrorField = f;
      if (err) newShakes[f] = (newShakes[f] || 0) + 1;
    });
    setTouched(newTouched);
    setShakeKey(newShakes);
    if (firstErrorField) return;

    // simulate submit
    setSubmitting(true);
    setTimeout(() => {
      setSubmitting(false);
      setSubmitted(true);
    }, 1100);
  };

  const steps = [
    {
      label: "Apresentação",
      content: (
        <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
          <Field
            name="nome" label="Como gosta de ser chamado(a)?"
            v={form.nome} onChange={v => update("nome", v)} onBlur={() => blur("nome")}
            placeholder="Seu nome"
            error={touched.nome ? errors.nome : null}
            valid={touched.nome && !errors.nome && form.nome.trim()}
            shakeKey={shakeKey.nome}
          />
          <Field
            name="email" type="email" label="E-mail de contato"
            v={form.email} onChange={v => update("email", v)} onBlur={() => blur("email")}
            placeholder="voce@exemplo.com"
            error={touched.email ? errors.email : null}
            valid={touched.email && !errors.email && form.email.trim()}
            shakeKey={shakeKey.email}
          />
          <Field
            name="oficio" label="Ofício / como se apresenta no mundo"
            v={form.oficio} onChange={v => update("oficio", v)} onBlur={() => blur("oficio")}
            placeholder="ex: designer, autora, fundadora..."
            error={touched.oficio ? errors.oficio : null}
            valid={touched.oficio && !errors.oficio && form.oficio.trim()}
            shakeKey={shakeKey.oficio}
          />
        </div>
      ),
    },
    {
      label: "Intenção",
      content: (
        <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
          <FieldArea
            name="intencao" label="Por que o Clube da Luz, e por que agora?"
            v={form.intencao} onChange={v => update("intencao", v)} onBlur={() => blur("intencao")}
            placeholder="Conte com suas palavras. Não procuramos respostas certas — procuramos honestidade."
            error={touched.intencao ? errors.intencao : null}
            valid={touched.intencao && !errors.intencao && form.intencao.trim().length >= 40}
            shakeKey={shakeKey.intencao}
            minLen={40}
          />
        </div>
      ),
    },
    {
      label: "Momento",
      content: (
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <div className="serial" style={{ marginBottom: 4 }}>∴ Em qual desses momentos você se reconhece hoje?</div>
          {[
            "Estou começando algo novo e preciso de método.",
            "Tenho um projeto pronto que ainda não veio ao mundo.",
            "Já entreguei muito; busco refinar voz e legado.",
            "Outro — explico na entrevista.",
          ].map((opt, i) => (
            <button
              key={i}
              type="button"
              data-field={i === 0 ? "momento" : undefined}
              onClick={() => { update("momento", opt); setTouched(t => ({ ...t, momento: true })); }}
              style={{
                padding: "16px 20px",
                textAlign: "left",
                border: form.momento === opt ? "1px solid var(--gold)" : "1px solid var(--line)",
                background: form.momento === opt ? "rgba(232,192,121,0.07)" : "transparent",
                borderRadius: 6,
                color: "var(--ivory)",
                fontSize: 14.5,
                transition: "all .25s",
                display: "flex",
                alignItems: "center",
                gap: 14,
              }}
            >
              <span className="serial" style={{ color: form.momento === opt ? "var(--gold)" : "var(--muted-2)" }}>0{i+1}</span>
              {opt}
            </button>
          ))}
          {touched.momento && errors.momento && (
            <div className="form-err">
              <ErrIcon /> {errors.momento}
            </div>
          )}
        </div>
      ),
    },
  ];

  const vw = window.useViewport();
  const isMobile = vw <= 820;

  if (submitted) {
    return (
      <section id="aplicar" style={{ padding: "140px 0", borderTop: "1px solid var(--line)", position: "relative", overflow: "hidden" }}>
        <div style={{
          position: "absolute", left: "50%", top: "30%", transform: "translateX(-50%)",
          width: 900, height: 900,
          background: "radial-gradient(circle, rgba(232,192,121,0.15) 0%, transparent 60%)",
          filter: "blur(40px)", pointerEvents: "none",
        }} />
        <div className="wrap-narrow" style={{ textAlign: "center", position: "relative" }}>
          <div style={{
            width: 72, height: 72, margin: "0 auto 28px",
            borderRadius: "50%", border: "1px solid var(--gold)",
            display: "flex", alignItems: "center", justifyContent: "center",
            background: "rgba(232,192,121,0.08)",
            animation: "checkPulse 1.6s ease-in-out infinite",
          }}>
            <svg width="28" height="28" viewBox="0 0 24 24" fill="none">
              <path d="M5 12l5 5L20 7" stroke="var(--gold)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </div>
          <h2 className="display" style={{ fontSize: "clamp(40px, 6vw, 64px)", lineHeight: 1.05, marginBottom: 22 }}>
            Sua aplicação<br />
            <span className="display-italic grad-gold">foi recebida</span>.
          </h2>
          <p style={{ fontSize: 16.5, color: "var(--ivory-dim)", maxWidth: 540, margin: "0 auto 36px", lineHeight: 1.7 }}>
            Lemos cada uma com atenção. Em até cinco dias úteis você recebe uma resposta —
            seja para agendar a entrevista, seja para conversarmos sobre o tempo certo.
          </p>
          <div className="serial" style={{ marginBottom: 28 }}>∴ {form.email}</div>
          <button
            className="btn"
            onClick={() => {
              setForm({ nome: "", email: "", oficio: "", intencao: "", momento: "" });
              setErrors({}); setTouched({}); setStep(0); setSubmitted(false);
            }}
            style={{ padding: "12px 22px" }}
          >
            Enviar outra aplicação
          </button>
        </div>
        <style>{`
          @keyframes checkPulse {
            0%,100% { box-shadow: 0 0 0 0 rgba(232,192,121,0.4); }
            50%     { box-shadow: 0 0 0 14px rgba(232,192,121,0); }
          }
        `}</style>
      </section>
    );
  }

  return (
    <section id="aplicar" style={{ padding: "120px 0", borderTop: "1px solid var(--line)", position: "relative", overflow: "hidden" }}>
      <div style={{
        position: "absolute",
        left: "50%", top: "30%", transform: "translateX(-50%)",
        width: 900, height: 900,
        background: "radial-gradient(circle, rgba(74,184,216,0.10) 0%, transparent 60%)",
        filter: "blur(40px)",
        pointerEvents: "none",
      }} />

      <div className="wrap">
        <div
          className="stack-mobile"
          style={{ display: "grid", gridTemplateColumns: "380px 1fr", gap: isMobile ? 48 : 80, alignItems: "start" }}
        >
          <div style={{ position: isMobile ? "static" : "sticky", top: 100 }}>
            <window.Reveal>
              <div className="eyebrow" style={{ marginBottom: 16 }}>— 06 · Aplicação</div>
              <h2 className="display" style={{ fontSize: "clamp(42px, 5vw, 64px)", lineHeight: 1.0, marginBottom: 22 }}>
                Solicite<br />
                <span className="display-italic grad-gold">acesso</span>.
              </h2>
              <p style={{ fontSize: 15, lineHeight: 1.7, color: "var(--ivory-dim)", marginBottom: 28 }}>
                Três passos curtos. Uma entrevista breve em vídeo. A decisão é mútua —
                se houver encaixe, você recebe o convite com o caminho de entrada.
              </p>
            </window.Reveal>

            <window.Reveal delay={1}>
              <div style={{ display: "flex", flexDirection: "column", gap: 0, borderTop: "1px solid var(--line)" }}>
                {steps.map((s, i) => (
                  <div key={i} style={{
                    padding: "14px 0",
                    borderBottom: "1px solid var(--line)",
                    display: "flex",
                    alignItems: "center",
                    gap: 16,
                    opacity: step >= i ? 1 : 0.4,
                    transition: "opacity .3s",
                  }}>
                    <div style={{
                      width: 26, height: 26, borderRadius: "50%",
                      border: step === i ? "1px solid var(--gold)" : "1px solid var(--line-strong)",
                      background: step > i ? "var(--gold)" : "transparent",
                      color: step > i ? "#061018" : (step === i ? "var(--gold)" : "var(--muted)"),
                      display: "flex", alignItems: "center", justifyContent: "center",
                      fontSize: 11, fontFamily: "var(--f-mono)",
                      transition: "all .3s",
                    }}>{step > i ? "✓" : `0${i+1}`}</div>
                    <span style={{ fontSize: 14, color: step === i ? "var(--ivory)" : "var(--muted)" }}>
                      {s.label}
                    </span>
                  </div>
                ))}
              </div>
            </window.Reveal>
          </div>

          <window.Reveal delay={1}>
            <div style={{
              background: "rgba(14,20,36,0.55)",
              border: "1px solid var(--line)",
              borderRadius: 6,
              padding: isMobile ? "32px 24px" : "44px",
              backdropFilter: "blur(12px)",
              position: "relative",
              zIndex: 2,
            }}>
              <div style={{
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
                marginBottom: 32,
                paddingBottom: 22,
                borderBottom: "1px solid var(--line)",
              }}>
                <div className="serial">∴ Passo {step + 1} de {steps.length}</div>
                <div className="serial">{steps[step].label.toUpperCase()}</div>
              </div>

              <div style={{ minHeight: 280 }}>
                {steps[step].content}
              </div>

              <div style={{
                display: "flex", justifyContent: "space-between", alignItems: "center",
                marginTop: 36, paddingTop: 22, borderTop: "1px solid var(--line)", gap: 12, flexWrap: "wrap"
              }}>
                <button
                  type="button"
                  onClick={() => setStep(Math.max(0, step - 1))}
                  className="btn"
                  style={{ visibility: step === 0 ? "hidden" : "visible" }}
                >
                  ← Voltar
                </button>
                {step < steps.length - 1 ? (
                  <button type="button" onClick={tryAdvance} className="btn btn-primary" style={{ padding: "13px 22px" }}>
                    Próximo passo
                    <svg className="btn-arrow" viewBox="0 0 24 24" fill="none">
                      <path d="M5 12h14M13 6l6 6-6 6" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
                    </svg>
                  </button>
                ) : (
                  <button
                    type="button"
                    onClick={trySubmit}
                    disabled={submitting}
                    className="btn btn-primary"
                    style={{ padding: "13px 22px", opacity: submitting ? 0.85 : 1, cursor: submitting ? "wait" : "pointer" }}
                  >
                    {submitting ? (
                      <>
                        <svg className="spin" width="14" height="14" viewBox="0 0 24 24" fill="none">
                          <circle cx="12" cy="12" r="9" stroke="currentColor" strokeOpacity="0.25" strokeWidth="2.5" />
                          <path d="M21 12a9 9 0 0 0-9-9" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" />
                        </svg>
                        Enviando…
                      </>
                    ) : (
                      <>
                        Enviar aplicação
                        <svg className="btn-arrow" viewBox="0 0 24 24" fill="none">
                          <path d="M5 12h14M13 6l6 6-6 6" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
                        </svg>
                      </>
                    )}
                  </button>
                )}
              </div>
            </div>
          </window.Reveal>
        </div>
      </div>

      <style>{`
        .form-err {
          display: flex; align-items: center; gap: 8px;
          color: #F4A8A8; font-size: 12.5px; font-family: var(--f-mono);
          letter-spacing: 0.04em; margin-top: 6px;
          animation: errFade .35s ease;
        }
        @keyframes errFade {
          from { opacity: 0; transform: translateY(-4px); }
          to   { opacity: 1; transform: translateY(0); }
        }
        .form-hint {
          display: flex; align-items: center; gap: 8px;
          color: var(--muted); font-size: 12px; font-family: var(--f-mono);
          letter-spacing: 0.04em; margin-top: 6px;
        }
        .form-ok {
          display: flex; align-items: center; gap: 8px;
          color: var(--gold); font-size: 12.5px; font-family: var(--f-mono);
          letter-spacing: 0.04em; margin-top: 6px;
          animation: errFade .3s ease;
        }
      `}</style>
    </section>
  );
}

function ErrIcon() {
  return (
    <svg width="13" height="13" viewBox="0 0 24 24" fill="none">
      <circle cx="12" cy="12" r="9.5" stroke="currentColor" strokeWidth="1.4" />
      <path d="M12 7v6M12 16v.5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
    </svg>
  );
}
function OkIcon() {
  return (
    <svg width="13" height="13" viewBox="0 0 24 24" fill="none">
      <circle cx="12" cy="12" r="9.5" stroke="currentColor" strokeWidth="1.4" />
      <path d="M7.5 12.5l3 3 6-6.5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function Field({ name, label, v, onChange, onBlur, placeholder, type = "text", error, valid, shakeKey }) {
  const ref = useRefC(null);
  const [animate, setAnimate] = useStateC(0);
  useEffectC(() => { if (shakeKey) setAnimate(k => k + 1); }, [shakeKey]);

  return (
    <label style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      <span className="serial">∴ {label}</span>
      <input
        ref={ref}
        data-field={name}
        type={type}
        value={v}
        onChange={e => onChange(e.target.value)}
        onBlur={onBlur}
        placeholder={placeholder}
        key={`${name}-${animate}`}
        className={shakeKey && error ? "shake" : ""}
        style={{
          background: "transparent",
          border: "none",
          borderBottom: error
            ? "1px solid #F4A8A8"
            : valid ? "1px solid var(--gold)"
            : "1px solid var(--line-strong)",
          padding: "12px 0",
          color: "var(--ivory)",
          fontSize: 17,
          fontFamily: "var(--f-display)",
          outline: "none",
          transition: "border-color .25s",
        }}
        onFocus={e => { if (!error) e.target.style.borderColor = "var(--aqua)"; }}
      />
      {error && <div className="form-err"><ErrIcon /> {error}</div>}
      {!error && valid && <div className="form-ok"><OkIcon /> Tudo certo.</div>}
    </label>
  );
}

function FieldArea({ name, label, v, onChange, onBlur, placeholder, error, valid, shakeKey, minLen }) {
  const ref = useRefC(null);
  const [animate, setAnimate] = useStateC(0);
  useEffectC(() => { if (shakeKey) setAnimate(k => k + 1); }, [shakeKey]);
  const len = (v || "").trim().length;
  const remaining = Math.max(0, (minLen || 0) - len);

  return (
    <label style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      <span className="serial">∴ {label}</span>
      <textarea
        ref={ref}
        data-field={name}
        value={v}
        onChange={e => onChange(e.target.value)}
        onBlur={onBlur}
        placeholder={placeholder}
        rows={6}
        key={`${name}-${animate}`}
        className={shakeKey && error ? "shake" : ""}
        style={{
          background: "rgba(255,255,255,0.02)",
          border: error ? "1px solid #F4A8A8" : valid ? "1px solid var(--gold)" : "1px solid var(--line)",
          borderRadius: 4,
          padding: "14px 16px",
          color: "var(--ivory)",
          fontSize: 15.5,
          fontFamily: "var(--f-ui)",
          outline: "none",
          resize: "vertical",
          transition: "border-color .25s",
          lineHeight: 1.6,
        }}
        onFocus={e => { if (!error) e.target.style.borderColor = "var(--aqua)"; }}
      />
      {error
        ? <div className="form-err"><ErrIcon /> {error}</div>
        : valid
          ? <div className="form-ok"><OkIcon /> Tudo certo · {len} caracteres.</div>
          : minLen
            ? <div className="form-hint">{remaining > 0 ? `Mínimo ${minLen} caracteres — faltam ${remaining}.` : `${len} caracteres.`}</div>
            : null
      }
    </label>
  );
}

/* ============================================================ */
/* Footer                                                       */
/* ============================================================ */
function Footer() {
  return (
    <footer style={{ borderTop: "1px solid var(--line)", padding: "70px 0 36px", position: "relative" }}>
      <div className="wrap">
        <div
          className="footer-grid"
          style={{ display: "grid", gridTemplateColumns: "2fr 1fr 1fr 1fr", gap: 48, marginBottom: 64 }}
        >
          <div>
            <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 22 }}>
              <window.Mark size={26} />
              <span className="display display-italic" style={{ fontSize: 28 }}>Clube da Luz</span>
            </div>
            <p style={{ fontSize: 14, lineHeight: 1.7, color: "var(--muted)", maxWidth: 360 }}>
              Um círculo privado para criadores que escolheram tornar visível
              o que sempre souberam. Conduzido por Adriano Ribeiro.
            </p>
          </div>
          <FooterCol title="Círculo" links={["Manifesto", "Trilhas", "Régua Criativa", "Mentor"]} />
          <FooterCol title="Acesso" links={["Aplicação", "Próxima imersão", "Calendário", "Perguntas"]} />
          <FooterCol title="Casa" links={["Adriano Ribeiro", "Eco.ar", "Comunidade JCS", "Imprensa"]} />
        </div>

        <div style={{
          paddingTop: 24,
          borderTop: "1px solid var(--line)",
          display: "flex",
          justifyContent: "space-between",
          color: "var(--muted-2)",
          fontFamily: "var(--f-mono)",
          fontSize: 10.5,
          letterSpacing: "0.1em",
          textTransform: "uppercase",
          flexWrap: "wrap", gap: 12,
        }}>
          <span>© MMXXVI · Clube da Luz · Rio de Janeiro / Lisboa</span>
          <div style={{ display: "flex", gap: 28 }}>
            <a href="#" style={{ color: "inherit" }}>Privacidade</a>
            <a href="#" style={{ color: "inherit" }}>Termos</a>
            <a href="#" style={{ color: "inherit" }}>Contato</a>
          </div>
        </div>

        {/* watermark */}
        <div style={{
          fontFamily: "var(--f-display)",
          fontStyle: "italic",
          fontSize: "clamp(96px, 22vw, 320px)",
          background: "linear-gradient(180deg, rgba(232,192,121,0.04) 0%, rgba(255,255,255,0.015) 100%)",
          WebkitBackgroundClip: "text", backgroundClip: "text",
          WebkitTextFillColor: "transparent", color: "transparent",
          textAlign: "center",
          marginTop: 36,
          lineHeight: 0.8,
          letterSpacing: "-0.04em",
          userSelect: "none",
        }}>
          Luz
        </div>
      </div>
    </footer>
  );
}

function FooterCol({ title, links }) {
  return (
    <div>
      <div className="serial" style={{ marginBottom: 18 }}>∴ {title}</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 11 }}>
        {links.map(l => (
          <a key={l} href="#" style={{ fontSize: 13.5, color: "var(--ivory-dim)", transition: "color .2s" }}>
            {l}
          </a>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { Aplicacao, Footer });
