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

const { useState: useStateContact, useEffect: useEffectContact } = React;

function ContactHeroES() {
  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 }}>Contacto</div>
            <h1 style={{ color: "#fff", maxWidth: "18ch", marginBottom: 24 }}>
              Solicite una <span style={{ color: "var(--red)" }}>Cotización</span>.
            </h1>
            <p className="lede" style={{ color: "rgba(255,255,255,0.72)", maxWidth: "50ch" }}>
              Respondemos en español, inglés y portugués en un día hábil. Nuestros ingenieros en Buenos Aires están listos para ayudarle a elegir el equipo de calibración correcto.
            </p>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 16, paddingTop: 8 }}>
            {[
              { icon: "mail",     label: "Email",     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: "Taller",    value: "Buenos Aires, Argentina",   href: null },
              { icon: "globe",    label: "Idiomas",   value: "Español · English · Português", 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 ContactFormSectionES() {
  const [submitted, setSubmitted] = useStateContact(false);
  const [loading, setLoading] = useStateContact(false);
  const [serverError, setServerError] = useStateContact(null);
  const [errors, setErrors] = useStateContact({});
  const [data, setData] = useStateContact({
    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] = "Requerido"; });
    if (data.email && !/^\S+@\S+\.\S+$/.test(data.email)) next.email = "Email inválido";
    setErrors(next);
    if (Object.keys(next).length > 0) return;
    setLoading(true);
    setServerError(null);
    try {
      await submitForm({
        ...data,
        _subject: `Cotización ES: ${data.product || "General"} — ${data.company}`,
      });
      setSubmitted(true);
    } catch {
      setServerError("Algo salió mal. Por favor intente nuevamente o envíenos un email a info@lonetti.com.ar");
    } finally {
      setLoading(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) => setData({ ...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 }}>Mensaje recibido.</h2>
        <p className="lede">Nuestro equipo le responderá dentro de dos días hábiles. Para requisitos urgentes, escríbanos por WhatsApp.</p>
        <a className="btn btn-ghost-dark" href="es/">Volver al inicio <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 un mensaje</div>
          <h2 className="h2" style={{ marginBottom: 20 }}>¿En qué podemos ayudarle?</h2>
          <p style={{ color: "var(--text-2)", lineHeight: 1.7, marginBottom: 32 }}>
            Ya sea que necesite una cotización, tenga una pregunta técnica sobre normas de calibración o quiera explorar una asociación de distribución — complete el formulario y un ingeniero lo contactará directamente.
          </p>
          <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
            {[
              { icon: "seal",     title: "Cotizaciones de calibración",   body: "Tanques probadores, medidas de prueba, configuraciones personalizadas." },
              { icon: "shipping", title: "Pedidos internacionales",       body: "Precios FOB/CIF, documentación, coordinación de flete." },
              { icon: "globe",    title: "Consultas de distribución",     body: "Exclusividad por país, capacitación, soporte de marketing." },
              { icon: "document", title: "Preguntas técnicas",            body: "Normas, clases de exactitud, ingeniería 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}/> Chateá con nosotros por 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", "Nombre 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", "Correo electrónico laboral", "email", true)}
          </div>
          {field("phone", "Teléfono (con código de 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)" }}>
              Producto de interés <span style={{ color: "var(--red)" }}>*</span>
            </span>
            <select value={data.product} onChange={(e) => setData({ ...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="">Seleccionar…</option>
              <option value="Tanques Probadores">Tanques Probadores</option>
              <option value="Medidas de Prueba">Medidas de Prueba</option>
              <option value="Sistema Water Draw">Sistema Water Draw</option>
              <option value="Torres para Cisternas">Torres para Cisternas</option>
              <option value="Banco de Calibración">Banco de Calibración</option>
              <option value="MINILAB®">MINILAB®</option>
              <option value="Otro">Otro</option>
            </select>
          </label>
          {field("capacity", "Capacidad requerida")}
          <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)" }}>
              Mensaje / Requerimientos personalizados
            </span>
            <textarea rows="4" value={data.message}
              onChange={(e) => setData({ ...data, message: e.target.value })}
              placeholder="Describa lo que necesita — tipo de producto, capacidad, clase de exactitud, normas aplicables, u otros detalles…"
              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 contacto preferida
            </span>
            <select value={data.contactPreference} onChange={(e) => setData({ ...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="">Seleccionar…</option>
              <option value="Correo electrónico">Correo electrónico</option>
              <option value="WhatsApp">WhatsApp</option>
              <option value="Llamada telefónica">Llamada 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 solicitud</span><Icon name="arrow" size={16} stroke="#fff"/></>}
          </button>
          <p style={{ margin: 0, fontSize: 12, color: "var(--text-3)", textAlign: "center" }}>
            Generalmente respondemos dentro de 2 días hábiles.
          </p>
        </form>
      </div>
    </section>
  );
}

function ContactPageES() {
  return (
    <>
      <Nav active="contact"/>
      <main>
        <ContactHeroES/>
        <ContactFormSectionES/>
      </main>
      <Footer/>
      <FloatingWhatsApp/>
    </>
  );
}

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