// pt/contact-page-pt.jsx — Portuguese Contact Page override.
// Loaded AFTER contact-page.jsx. Replaces window.ContactPage with Portuguese version.

const { useState: useStateContactPT, useEffect: useEffectContactPT } = React;

function ContactHeroPT() {
  return (
    <section className="surface-dark grid-bg" style={{ paddingTop: 80, paddingBottom: 80 }}>
      <div className="container">
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 80, alignItems: "start" }}>
          <div>
            <div className="eyebrow on-dark" style={{ marginBottom: 22 }}>Contato</div>
            <h1 style={{ color: "#fff", maxWidth: "18ch", marginBottom: 24 }}>
              Solicite uma <span style={{ color: "var(--red)" }}>Cotação</span>.
            </h1>
            <p className="lede" style={{ color: "rgba(255,255,255,0.72)", maxWidth: "50ch" }}>
              Respondemos em português, inglês e espanhol em um dia útil. Nossos engenheiros em Buenos Aires estão prontos para ajudá-lo a escolher o equipamento de calibração correto.
            </p>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 16, paddingTop: 8 }}>
            {[
              { icon: "mail",     label: "E-mail",    value: "info@lonetti.com.ar",         href: "mailto:info@lonetti.com.ar" },
              { icon: "whatsapp", label: "WhatsApp",  value: "+54 9 11 2788 4190",          href: "https://wa.me/5491127884190" },
              { icon: "pin",      label: "Fábrica",   value: "Buenos Aires, Argentina",     href: null },
              { icon: "globe",    label: "Idiomas",   value: "Português · English · Español", href: null },
            ].map((c) => (
              <div key={c.label} style={{
                display: "flex", alignItems: "center", gap: 18,
                background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.12)",
                borderRadius: 6, padding: "18px 22px",
              }}>
                <div style={{ width: 40, height: 40, borderRadius: 4, background: "rgba(255,255,255,0.08)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--red)", flexShrink: 0 }}>
                  <Icon name={c.icon} size={20}/>
                </div>
                <div>
                  <div className="mono" style={{ fontSize: 10, letterSpacing: "0.12em", color: "rgba(255,255,255,0.45)", textTransform: "uppercase", marginBottom: 4 }}>{c.label}</div>
                  {c.href ? (
                    <a href={c.href} style={{ fontSize: 15, fontWeight: 600, color: "#fff" }}>{c.value}</a>
                  ) : (
                    <span style={{ fontSize: 15, fontWeight: 600, color: "#fff" }}>{c.value}</span>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function ContactFormSectionPT() {
  const [submitted, setSubmittedPTForm] = useStateContactPT(false);
  const [loading, setLoadingPTForm] = useStateContactPT(false);
  const [serverError, setServerErrorPTForm] = useStateContactPT(null);
  const [errors, setErrorsPTForm] = useStateContactPT({});
  const [data, setDataPTForm] = useStateContactPT({
    name: "", company: "", country: "", email: "",
    phone: "", product: "", capacity: "", message: "", contactPreference: ""
  });

  const onSubmit = async (e) => {
    e.preventDefault();
    const next = {};
    ["name", "company", "country", "email"].forEach((k) => { if (!data[k]) next[k] = "Obrigatório"; });
    if (data.email && !/^\S+@\S+\.\S+$/.test(data.email)) next.email = "E-mail inválido";
    setErrorsPTForm(next);
    if (Object.keys(next).length > 0) return;
    setLoadingPTForm(true);
    setServerErrorPTForm(null);
    try {
      await submitForm({
        ...data,
        _subject: `Cotação PT: ${data.product || "Geral"} — ${data.company}`,
      });
      setSubmittedPTForm(true);
    } catch {
      setServerErrorPTForm("Ocorreu um erro. Por favor, tente novamente ou envie um e-mail para info@lonetti.com.ar");
    } finally {
      setLoadingPTForm(false);
    }
  };

  const field = (k, label, type = "text", required = false) => (
    <label style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      <span style={{ fontSize: 11, fontFamily: "var(--f-mono)", letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--text-3)" }}>
        {label}{required && <span style={{ color: "var(--red)", marginLeft: 4 }}>*</span>}
      </span>
      <input type={type} value={data[k]} onChange={(e) => setDataPTForm({ ...data, [k]: e.target.value })}
        style={{
          padding: "12px 14px", background: "#fff",
          border: `1px solid ${errors[k] ? "var(--red)" : "var(--line)"}`,
          borderRadius: 4, color: "var(--text)", fontSize: 14, fontFamily: "var(--f-body)",
        }}/>
      {errors[k] && <span style={{ fontSize: 11, color: "var(--red)" }}>{errors[k]}</span>}
    </label>
  );

  if (submitted) {
    return (
      <div style={{
        maxWidth: 560, margin: "0 auto", padding: "64px 0",
        display: "flex", flexDirection: "column", alignItems: "center", textAlign: "center", gap: 20,
      }}>
        <div style={{ width: 64, height: 64, borderRadius: "50%", background: "var(--red)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center" }}>
          <Icon name="check" size={30} stroke="#fff" strokeWidth={2}/>
        </div>
        <h2 className="h2" style={{ fontSize: 36 }}>Mensagem recebida.</h2>
        <p className="lede">Nossa equipe responderá dentro de dois dias úteis. Para requisitos urgentes, escreva-nos pelo WhatsApp.</p>
        <a className="btn btn-ghost-dark" href="pt/">Voltar ao início <Icon name="arrow" size={16}/></a>
      </div>
    );
  }

  return (
    <section>
      <div className="container" style={{ display: "grid", gridTemplateColumns: "1fr 1.4fr", gap: 80, alignItems: "start" }}>
        <div style={{ paddingTop: 8 }}>
          <div className="eyebrow" style={{ marginBottom: 18 }}>Enviar uma mensagem</div>
          <h2 className="h2" style={{ marginBottom: 20 }}>Como podemos ajudá-lo?</h2>
          <p style={{ color: "var(--text-2)", lineHeight: 1.7, marginBottom: 32 }}>
            Seja para uma cotação, uma dúvida técnica sobre normas de calibração ou para explorar uma parceria de distribuição — preencha o formulário e um engenheiro entrará em contato diretamente.
          </p>
          <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
            {[
              { icon: "seal",     title: "Cotações de calibração",    body: "Tanques provadores, medidas de teste, configurações personalizadas." },
              { icon: "shipping", title: "Pedidos internacionais",    body: "Preços FOB/CIF, documentação, coordenação de frete para o Brasil." },
              { icon: "globe",    title: "Consultas de distribuição", body: "Exclusividade por país, treinamento, suporte de marketing." },
              { icon: "document", title: "Dúvidas técnicas",         body: "Normas, classes de exatidão, engenharia personalizada." },
            ].map((it) => (
              <div key={it.title} style={{ display: "flex", gap: 14, alignItems: "flex-start" }}>
                <div style={{ width: 36, height: 36, borderRadius: 4, background: "var(--bg-alt)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--navy)", flexShrink: 0, marginTop: 2 }}>
                  <Icon name={it.icon} size={18}/>
                </div>
                <div>
                  <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 4 }}>{it.title}</div>
                  <div style={{ fontSize: 13, color: "var(--text-2)", lineHeight: 1.5 }}>{it.body}</div>
                </div>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 36 }}>
            <a href="https://wa.me/5491127884190" target="_blank" rel="noopener noreferrer"
              className="btn btn-ghost-dark" style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
              <Icon name="whatsapp" size={18}/> Fale conosco pelo WhatsApp
            </a>
          </div>
        </div>

        <form onSubmit={onSubmit} style={{
          background: "var(--bg-alt)", border: "1px solid var(--line)", borderRadius: 8,
          padding: 40, display: "flex", flexDirection: "column", gap: 18,
        }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            {field("name", "Nome completo", "text", true)}
            {field("company", "Empresa", "text", true)}
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            {field("country", "País", "text", true)}
            {field("email", "E-mail profissional", "email", true)}
          </div>
          {field("phone", "Telefone (com código do país)", "tel")}
          <label style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            <span style={{ fontSize: 11, fontFamily: "var(--f-mono)", letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--text-3)" }}>
              Produto de interesse <span style={{ color: "var(--red)" }}>*</span>
            </span>
            <select value={data.product} onChange={(e) => setDataPTForm({ ...data, product: e.target.value })}
              style={{ padding: "12px 14px", background: "#fff", border: "1px solid var(--line)", borderRadius: 4, color: "var(--text)", fontSize: 14, fontFamily: "var(--f-body)" }}>
              <option value="">Selecionar…</option>
              <option value="Tanques Provadores">Tanques Provadores</option>
              <option value="Medidas de Teste">Medidas de Teste</option>
              <option value="Sistema Water Draw">Sistema Water Draw</option>
              <option value="Torres para Caminhões-Tanque">Torres para Caminhões-Tanque</option>
              <option value="Bancada de Calibração">Bancada de Calibração</option>
              <option value="MINILAB®">MINILAB®</option>
              <option value="Outro">Outro</option>
            </select>
          </label>
          {field("capacity", "Capacidade necessária")}
          <label style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            <span style={{ fontSize: 11, fontFamily: "var(--f-mono)", letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--text-3)" }}>
              Mensagem / Requisitos customizados
            </span>
            <textarea rows="4" value={data.message}
              onChange={(e) => setDataPTForm({ ...data, message: e.target.value })}
              placeholder="Descreva o que você precisa — tipo de produto, capacidade, classe de exatidão, normas aplicáveis, ou outros detalhes…"
              style={{ padding: "12px 14px", background: "#fff", border: "1px solid var(--line)", borderRadius: 4, color: "var(--text)", fontSize: 14, fontFamily: "var(--f-body)", resize: "vertical" }}/>
          </label>
          <label style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            <span style={{ fontSize: 11, fontFamily: "var(--f-mono)", letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--text-3)" }}>
              Forma de contato preferida
            </span>
            <select value={data.contactPreference} onChange={(e) => setDataPTForm({ ...data, contactPreference: e.target.value })}
              style={{ padding: "12px 14px", background: "#fff", border: "1px solid var(--line)", borderRadius: 4, color: "var(--text)", fontSize: 14, fontFamily: "var(--f-body)" }}>
              <option value="">Selecionar…</option>
              <option value="E-mail">E-mail</option>
              <option value="WhatsApp">WhatsApp</option>
              <option value="Ligação telefônica">Ligação telefônica</option>
            </select>
          </label>
          {serverError && (
            <p style={{ margin: 0, fontSize: 13, color: "var(--red)", background: "var(--red-soft)", padding: "10px 14px", borderRadius: 4 }}>
              {serverError}
            </p>
          )}
          <button type="submit" disabled={loading} className="btn btn-primary" style={{
            marginTop: 4, justifyContent: "center",
            opacity: loading ? 0.7 : 1, cursor: loading ? "not-allowed" : "pointer",
          }}>
            {loading ? "Enviando…" : <><span>Enviar solicitação</span><Icon name="arrow" size={16} stroke="#fff"/></>}
          </button>
          <p style={{ margin: 0, fontSize: 12, color: "var(--text-3)", textAlign: "center" }}>
            Geralmente respondemos dentro de 2 dias úteis.
          </p>
        </form>
      </div>
    </section>
  );
}

function ContactPagePT() {
  return (
    <>
      <Nav active="contact"/>
      <main>
        <ContactHeroPT/>
        <ContactFormSectionPT/>
      </main>
      <Footer/>
      <FloatingWhatsApp/>
    </>
  );
}

Object.assign(window, { ContactPage: ContactPagePT });
