// about-contact.jsx — About + Contact (typeform-style)
const { useState: uState, useEffect: uEffect, useRef: uRef } = React;

/* ============================================================
   About
   ============================================================ */
function About({ t, lang, navigate }) {
  const ref = uRef(null);
  uEffect(() => {
    if (!ref.current) return;
    gsap.fromTo(ref.current.querySelectorAll("[data-fade]"),
      { y: 40, opacity: 0 },
      { y: 0, opacity: 1, duration: 1, ease: "expo.out", stagger: 0.06, delay: 0.1 }
    );
  }, [lang]);

  return (
    <section data-screen-label="about" ref={ref} style={{ position: "relative" }}>
      <CircleMotif top="20%" right="-180px" size={500} opacity={0.15} />
      <CircleMotif bottom="-100px" left="-80px" size={300} opacity={0.18} />

      {/* Header */}
      <div style={{ padding: "60px var(--gutter) 40px" }}>
        <div data-fade className="mono" style={{ color: "var(--muted)", marginBottom: 30 }}>{t.about.kicker}</div>
        <h1 data-fade style={{
          fontSize: "clamp(56px, 10vw, 160px)",
          fontWeight: 500,
          letterSpacing: "-0.04em",
          lineHeight: 0.9,
          marginBottom: 60,
        }}>
          <span>{t.about.title}</span>
          <span className="italic-serif" style={{ marginLeft: "0.3em" }}>—</span>
        </h1>
      </div>

      {/* Hero: portrait + bio */}
      <div style={{ padding: "0 var(--gutter) 80px", display: "grid", gridTemplateColumns: "1.1fr 0.9fr", gap: 80, alignItems: "start" }}>
        <div data-fade>
          <p style={{ fontSize: "clamp(20px, 1.7vw, 28px)", lineHeight: 1.4, marginBottom: 28, letterSpacing: "-0.01em", textWrap: "pretty" }}>
            {t.about.bio}
          </p>
          <p style={{ fontSize: "clamp(16px, 1.1vw, 18px)", lineHeight: 1.6, color: "var(--muted)", textWrap: "pretty" }}>
            {t.about.bio2}
          </p>
        </div>
        <div data-fade>
          <div style={{ position: "relative", aspectRatio: "3/4", overflow: "hidden", borderRadius: 4, background: "#0a0a0a" }}>
            <img src="assets/portrait.jpg" alt="Fabrício Parra" style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }}/>
            <div style={{
              position: "absolute", inset: 0,
              backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='2'/><feColorMatrix values='0 0 0 0 0  0 0 0 0 0  0 0 0 0 0  0 0 0 0.4 0'/></filter><rect width='100%25' height='100%25' filter='url(%23n)'/></svg>\")",
              mixBlendMode: "multiply", opacity: 0.25, pointerEvents: "none",
            }}/>
            <div style={{ position: "absolute", bottom: 20, left: 20, right: 20, display: "flex", justifyContent: "space-between", alignItems: "flex-end", color: "#f6f5f2", textShadow: "0 2px 12px rgba(0,0,0,0.5)" }}>
              <div className="mono" style={{ opacity: 0.85, fontSize: 10, letterSpacing: "0.1em" }}>FLORENÇA, IT · 2025</div>
              <div className="mono" style={{ opacity: 0.85, fontSize: 10, letterSpacing: "0.1em" }}>F. PARRA</div>
            </div>
          </div>
        </div>
      </div>

      {/* Experience */}
      <div style={{ padding: "60px var(--gutter)", borderTop: "1px solid var(--hairline)" }}>
        <div data-fade style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 48, flexWrap: "wrap", gap: 16 }}>
          <h2 style={{ fontSize: "var(--t-h2)", fontWeight: 500, letterSpacing: "-0.02em" }}>
            {t.about.experienceTitle}<span className="italic-serif" style={{ marginLeft: 6 }}>.</span>
          </h2>
          <span className="mono" style={{ color: "var(--muted)" }}>{String(t.about.experience.length).padStart(2,"0")} {lang === "pt" ? "posições" : "positions"}</span>
        </div>
        <div>
          {t.about.experience.map((exp, i) => (
            <article key={i} data-fade style={{
              display: "grid",
              gridTemplateColumns: "220px 1fr",
              gap: 40,
              padding: "32px 0",
              borderTop: "1px solid var(--hairline)",
            }}>
              <div className="mono" style={{ color: "var(--muted)", fontSize: 12, letterSpacing: "0.04em" }}>{exp.period}</div>
              <div>
                <h3 style={{ fontSize: "clamp(22px, 2vw, 30px)", fontWeight: 500, letterSpacing: "-0.02em", marginBottom: 6 }}>{exp.role}</h3>
                <div className="mono" style={{ color: "var(--muted)", marginBottom: 14 }}>{exp.company}</div>
                <p style={{ fontSize: "clamp(15px, 1.05vw, 17px)", lineHeight: 1.55, color: "var(--ink-soft)", maxWidth: 760, textWrap: "pretty" }}>{exp.desc}</p>
              </div>
            </article>
          ))}
        </div>
      </div>

      {/* Education */}
      <div style={{ padding: "60px var(--gutter)", borderTop: "1px solid var(--hairline)" }}>
        <div data-fade style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 48, flexWrap: "wrap", gap: 16 }}>
          <h2 style={{ fontSize: "var(--t-h2)", fontWeight: 500, letterSpacing: "-0.02em" }}>
            {t.about.educationTitle}<span className="italic-serif" style={{ marginLeft: 6 }}>.</span>
          </h2>
        </div>
        <div>
          {t.about.education.map((edu, i) => (
            <article key={i} data-fade style={{
              display: "grid",
              gridTemplateColumns: "220px 1fr",
              gap: 40,
              padding: "26px 0",
              borderTop: "1px solid var(--hairline)",
            }}>
              <div className="mono" style={{ color: "var(--muted)", fontSize: 12, letterSpacing: "0.04em" }}>{edu.period}</div>
              <div>
                <h3 style={{ fontSize: "clamp(20px, 1.8vw, 28px)", fontWeight: 500, letterSpacing: "-0.02em", marginBottom: 6 }}>{edu.course}</h3>
                <div className="mono" style={{ color: "var(--muted)" }}>{edu.school}</div>
              </div>
            </article>
          ))}
        </div>
      </div>

      {/* Languages · Certifications · Tools */}
      <div style={{ padding: "60px var(--gutter)", borderTop: "1px solid var(--hairline)", display: "grid", gridTemplateColumns: "1fr 1fr 1.4fr", gap: 60 }}>
        <div data-fade>
          <div className="mono" style={{ color: "var(--muted)", marginBottom: 22 }}>{t.about.languagesTitle}</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {t.about.languages.map((l, i) => (
              <div key={i} style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", borderBottom: "1px solid var(--hairline)", paddingBottom: 12 }}>
                <span style={{ fontSize: "clamp(17px, 1.3vw, 20px)", fontWeight: 500 }}>{l.name}</span>
                <span className="mono" style={{ color: "var(--muted)" }}>{l.level}</span>
              </div>
            ))}
          </div>
        </div>
        <div data-fade>
          <div className="mono" style={{ color: "var(--muted)", marginBottom: 22 }}>{t.about.certificationsTitle}</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {t.about.certifications.map((c, i) => (
              <div key={i} style={{ fontSize: "clamp(17px, 1.3vw, 20px)", fontWeight: 500, borderBottom: "1px solid var(--hairline)", paddingBottom: 12 }}>
                {c}
              </div>
            ))}
          </div>
        </div>
        <div data-fade>
          <div className="mono" style={{ color: "var(--muted)", marginBottom: 22 }}>{t.about.toolsTitle}</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            {t.about.toolsList.map((s, i) => (
              <span key={i} className="mono" style={{ padding: "8px 14px", border: "1px solid var(--hairline-strong)", borderRadius: 999 }}>{s}</span>
            ))}
          </div>
        </div>
      </div>

      {/* Now / availability */}
      <div style={{ padding: "60px var(--gutter) 100px", borderTop: "1px solid var(--hairline)", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 60, alignItems: "center" }}>
        <div data-fade>
          <div className="mono" style={{ color: "var(--muted)", marginBottom: 16 }}>{t.about.now}</div>
          <p style={{ fontSize: "clamp(28px, 3.5vw, 52px)", lineHeight: 1.1, letterSpacing: "-0.02em", fontWeight: 500 }}>
            {t.about.nowText}
          </p>
        </div>
        <div data-fade style={{ display: "flex", justifyContent: "flex-end" }}>
          <span className="mono" style={{
            display: "inline-flex", alignItems: "center", gap: 10,
            padding: "12px 20px",
            border: "1px solid var(--hairline-strong)",
            borderRadius: 999,
          }}>
            <span style={{ width: 8, height: 8, borderRadius: "50%", background: "#16a34a", boxShadow: "0 0 0 4px rgba(22,163,74,0.2)" }}/>
            {lang === "pt" ? "Aceitando projetos" : "Accepting projects"}
          </span>
        </div>
      </div>

      <CTAStrip t={t} navigate={navigate} lang={lang}/>
    </section>
  );
}

function CTAStrip({ t, navigate, lang }) {
  return (
    <div style={{
      padding: "120px var(--gutter)",
      borderTop: "1px solid var(--hairline)",
      borderBottom: "1px solid var(--hairline)",
      display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 40,
    }}>
      <div>
        <div className="mono" style={{ color: "var(--muted)", marginBottom: 14 }}>(↓)</div>
        <h2 style={{ fontSize: "clamp(36px, 6vw, 88px)", fontWeight: 500, letterSpacing: "-0.03em", lineHeight: 0.95 }}>
          {lang === "pt" ? <>Vamos criar <span className="italic-serif">algo</span><br/>memorável<span className="italic-serif">.</span></> : <>Let's build <span className="italic-serif">something</span><br/>memorable<span className="italic-serif">.</span></>}
        </h2>
      </div>
      <button className="btn btn-solid" onClick={() => navigate("contact")} style={{ fontSize: 16, padding: "20px 32px" }}>
        <span>{t.nav.contact}</span><span className="arrow"><Arrow/></span>
      </button>
    </div>
  );
}

/* ============================================================
   Contact — Typeform-style
   ============================================================ */
function Contact({ t, lang }) {
  const [step, setStep] = uState(0);
  const [data, setData] = uState({ name: "", whatsapp: "", email: "", budget: "", message: "" });
  const [done, setDone] = uState(false);
  const [sending, setSending] = uState(false);
  const [error, setError] = uState(null);
  const inputRef = uRef(null);
  const sectionRef = uRef(null);

  const fields = [
    { key: "name", q: t.contact.q1, kind: "text", type: "text" },
    { key: "whatsapp", q: t.contact.q2, kind: "text", type: "tel" },
    { key: "email", q: t.contact.q3, kind: "text", type: "email" },
    { key: "budget", q: t.contact.q4, kind: "options" },
    { key: "message", q: t.contact.q5, kind: "textarea" },
  ];

  uEffect(() => {
    if (inputRef.current) inputRef.current.focus();
    // animate question in
    const cur = sectionRef.current?.querySelector("[data-step-active]");
    if (cur) gsap.fromTo(cur, { y: 30, opacity: 0 }, { y: 0, opacity: 1, duration: 0.7, ease: "expo.out" });
  }, [step, done]);

  const validate = () => {
    const f = fields[step];
    const v = data[f.key];
    if (!v || !v.trim()) return false;
    if (f.key === "email") return /\S+@\S+\.\S+/.test(v);
    return true;
  };

  const submitForm = async () => {
    setSending(true);
    setError(null);
    try {
      const payload = {
        access_key: "b0148534-8e75-4638-a33a-c63917911c03",
        subject: `Novo contato pelo portfólio — ${data.name}`,
        from_name: "Portfólio Fabrício Parra",
        replyto: data.email,
        name: data.name,
        whatsapp: data.whatsapp,
        email: data.email,
        budget: data.budget,
        message: data.message,
      };
      const res = await fetch("https://api.web3forms.com/submit", {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify(payload),
      });
      const json = await res.json();
      if (json && json.success) {
        setDone(true);
      } else {
        setError(json && json.message ? json.message : "submit_failed");
      }
    } catch (e) {
      setError(String(e && e.message || e));
    } finally {
      setSending(false);
    }
  };

  const onNext = () => {
    if (!validate() || sending) return;
    if (step < fields.length - 1) setStep(step + 1);
    else submitForm();
  };

  const onBack = () => { if (step > 0 && !sending) setStep(step - 1); };

  const onKey = (e) => {
    if (e.key === "Enter" && !e.shiftKey && fields[step].kind !== "textarea") {
      e.preventDefault();
      onNext();
    } else if (e.key === "Enter" && e.metaKey) {
      e.preventDefault();
      onNext();
    }
  };

  const progress = ((step + (done ? 1 : 0)) / fields.length) * 100;
  const f = fields[step];

  if (done) {
    return (
      <section data-screen-label="contact-done" style={{ minHeight: "calc(100vh - 90px)", padding: "60px var(--gutter)", display: "flex", alignItems: "center", justifyContent: "center" }}>
        <div data-step-active style={{ maxWidth: 720, textAlign: "center" }}>
          <div style={{ fontSize: 64, marginBottom: 20 }}>
            <span style={{ display: "inline-block", width: 80, height: 80, borderRadius: "50%", background: "var(--ink)", color: "var(--inv)", lineHeight: "80px", fontSize: 36 }}>✓</span>
          </div>
          <h1 style={{ fontSize: "clamp(40px, 6vw, 80px)", fontWeight: 500, letterSpacing: "-0.03em", lineHeight: 1, marginBottom: 24 }}>
            {t.contact.done.title.split(" ")[0]} <span className="italic-serif">{t.contact.done.title.split(" ").slice(1).join(" ")}</span>
          </h1>
          <p style={{ fontSize: "clamp(16px, 1.2vw, 20px)", color: "var(--muted)", maxWidth: 520, margin: "0 auto 40px", lineHeight: 1.5 }}>{t.contact.done.body}</p>
          <button className="btn" onClick={() => { setDone(false); setStep(0); setData({ name: "", whatsapp: "", email: "", budget: "", message: "" }); setError(null); }}>
            {t.contact.done.restart}
          </button>
        </div>
      </section>
    );
  }

  return (
    <section data-screen-label="contact" ref={sectionRef} style={{ minHeight: "calc(100vh - 90px)", display: "flex", flexDirection: "column", padding: "60px var(--gutter) 0" }}>
      {/* Header */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 60 }}>
        <div>
          <div className="mono" style={{ color: "var(--muted)", marginBottom: 8 }}>{t.contact.step} {String(step + 1).padStart(2, "0")} {t.contact.of} {String(fields.length).padStart(2, "0")}</div>
          <h2 style={{ fontSize: "clamp(28px, 3vw, 40px)", fontWeight: 500, letterSpacing: "-0.02em", lineHeight: 1 }}>
            {t.contact.title.split(" ")[0]} <span className="italic-serif">{t.contact.title.split(" ").slice(1).join(" ")}</span>
          </h2>
        </div>
        <div style={{ width: 200, maxWidth: "30%" }}>
          <div style={{ height: 1, background: "var(--hairline)", position: "relative" }}>
            <div style={{ height: 1, background: "var(--ink)", width: `${progress}%`, transition: "width 0.6s var(--ease)" }}/>
          </div>
          <div className="mono" style={{ color: "var(--muted)", marginTop: 10, textAlign: "right" }}>{Math.round(progress)}%</div>
        </div>
      </div>

      {/* Question */}
      <div style={{ flex: 1, display: "flex", alignItems: "center", maxWidth: 920 }}>
        <div data-step-active key={step} style={{ width: "100%" }}>
          <div className="mono" style={{ color: "var(--muted)", marginBottom: 20, display: "inline-flex", alignItems: "center", gap: 8 }}>
            <span>{f.q.label}</span>
            <span style={{ display: "inline-block", transform: "rotate(90deg)" }}><Arrow size={10}/></span>
          </div>
          <h3 style={{ fontSize: "clamp(32px, 5vw, 64px)", fontWeight: 500, letterSpacing: "-0.03em", lineHeight: 1.05, marginBottom: 36 }}>
            {f.q.title}
          </h3>

          {f.kind === "text" && (
            <input
              ref={inputRef}
              type={f.type}
              value={data[f.key]}
              onChange={e => setData({ ...data, [f.key]: e.target.value })}
              onKeyDown={onKey}
              placeholder={f.q.placeholder}
              style={{
                width: "100%",
                background: "transparent",
                border: "none",
                outline: "none",
                borderBottom: "1px solid var(--hairline-strong)",
                padding: "16px 0",
                fontSize: "clamp(22px, 2.6vw, 36px)",
                fontFamily: "inherit",
                color: "var(--ink)",
                letterSpacing: "-0.01em",
              }}
            />
          )}

          {f.kind === "textarea" && (
            <textarea
              ref={inputRef}
              value={data[f.key]}
              onChange={e => setData({ ...data, [f.key]: e.target.value })}
              onKeyDown={onKey}
              placeholder={f.q.placeholder}
              rows={4}
              style={{
                width: "100%",
                background: "transparent",
                border: "none",
                outline: "none",
                borderBottom: "1px solid var(--hairline-strong)",
                padding: "16px 0",
                fontSize: "clamp(20px, 2vw, 28px)",
                fontFamily: "inherit",
                color: "var(--ink)",
                letterSpacing: "-0.01em",
                resize: "none",
              }}
            />
          )}

          {f.kind === "options" && (
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, maxWidth: 700 }}>
              {f.q.options.map((opt, i) => {
                const sel = data[f.key] === opt;
                return (
                  <button key={i}
                    onClick={() => { setData({ ...data, [f.key]: opt }); setTimeout(onNext, 250); }}
                    style={{
                      textAlign: "left",
                      padding: "22px 26px",
                      border: `1px solid ${sel ? "var(--ink)" : "var(--hairline-strong)"}`,
                      borderRadius: 4,
                      background: sel ? "var(--ink)" : "transparent",
                      color: sel ? "var(--inv)" : "var(--ink)",
                      fontSize: "clamp(18px, 1.5vw, 22px)",
                      letterSpacing: "-0.01em",
                      cursor: "pointer",
                      display: "flex", justifyContent: "space-between", alignItems: "center", gap: 14,
                      transition: "all 0.3s var(--ease)",
                    }}>
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 14 }}>
                      <span className="mono" style={{
                        width: 28, height: 28,
                        border: `1px solid ${sel ? "var(--inv)" : "var(--hairline-strong)"}`,
                        borderRadius: 4,
                        display: "inline-flex", alignItems: "center", justifyContent: "center",
                        fontSize: 11,
                      }}>{String.fromCharCode(65 + i)}</span>
                      {opt}
                    </span>
                    {sel && <Arrow size={14}/>}
                  </button>
                );
              })}
            </div>
          )}
        </div>
      </div>

      {/* Footer / nav */}
      <div style={{ padding: "40px 0", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 14, flexWrap: "wrap", borderTop: "1px solid var(--hairline)" }}>
        <div className="mono" style={{ color: error ? "#b03a2e" : "var(--muted)", maxWidth: 480 }}>
          {error
            ? `${t.contact.error.title} ${t.contact.error.body}`
            : sending
              ? t.contact.sending
              : (f.kind !== "options" && t.contact.enterToContinue)}
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          <button className="btn" onClick={onBack} disabled={step === 0 || sending} style={{ opacity: (step === 0 || sending) ? 0.4 : 1, cursor: (step === 0 || sending) ? "not-allowed" : "pointer" }}>
            <span style={{ display: "inline-block", transform: "rotate(180deg)" }}><Arrow size={12}/></span>
            <span>{t.contact.back}</span>
          </button>
          <button className="btn btn-solid" onClick={onNext} disabled={!validate() || sending} style={{ opacity: (validate() && !sending) ? 1 : 0.5 }}>
            <span>{sending ? t.contact.sending : (step === fields.length - 1 ? (error ? t.contact.error.retry : t.contact.submit) : t.contact.next)}</span>
            <span className="arrow">
              {sending
                ? <span style={{ display: "inline-block", width: 12, height: 12, border: "1.5px solid currentColor", borderTopColor: "transparent", borderRadius: "50%", animation: "spin 0.8s linear infinite" }}/>
                : <Arrow size={12}/>}
            </span>
          </button>
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   Footer
   ============================================================ */
function Footer({ t, lang, navigate }) {
  return (
    <footer style={{ borderTop: "1px solid var(--hairline)", padding: "60px var(--gutter) 30px", marginTop: 0 }}>
      <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr 1fr", gap: 40, marginBottom: 60 }}>
        <div>
          <h3 style={{ fontSize: "clamp(40px, 6vw, 88px)", fontWeight: 500, letterSpacing: "-0.03em", lineHeight: 0.9 }}>
            Fabrício <span className="italic-serif">Parra</span><span style={{ display: "inline-block", width: "0.3em", height: "0.3em", borderRadius: "50%", background: "currentColor", verticalAlign: "middle", marginLeft: "0.2em" }}/>
          </h3>
        </div>
        <div>
          <div className="mono" style={{ color: "var(--muted)", marginBottom: 12 }}>{t.footer.basedIn}</div>
          <div className="mono" style={{ color: "var(--muted)" }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
              <span style={{ width: 8, height: 8, borderRadius: "50%", background: "#16a34a" }}/>{t.footer.avail}
            </span>
          </div>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 10, alignItems: "flex-end" }}>
          <a href="mailto:fabricio.pagotto1@gmail.com" style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
            {t.footer.mail} <Arrow size={12}/>
          </a>
          <a href="https://www.linkedin.com/in/fabricio-parra-2b0237202/" target="_blank" rel="noopener" style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
            {t.footer.linkedin} <Arrow size={12}/>
          </a>
        </div>
      </div>
      <div style={{ borderTop: "1px solid var(--hairline)", paddingTop: 24, display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 14 }}>
        <span className="mono" style={{ color: "var(--muted)" }}>{t.footer.copy}</span>
        <span className="mono" style={{ color: "var(--muted)" }}>fabricio.pagotto1@gmail.com</span>
      </div>
    </footer>
  );
}

Object.assign(window, { About, CTAStrip, Contact, Footer });
