/* construccion-cta.jsx — CTA "Agendar conversación" (HubSpot) + Footer */

/* HubSpot Forms — submission endpoint (public, CORS-enabled) */
const HS_PORTAL_ID = "143803870";
const HS_FORM_GUID = "a1b69c32-837f-4067-a87f-72dafec77eba";
const HS_ENDPOINT = `https://api.hsforms.com/submissions/v3/integration/submit/${HS_PORTAL_ID}/${HS_FORM_GUID}`;

/* ============================================================ */
/*  CTA · AGENDAR CONVERSACIÓN                                   */
/* ============================================================ */

function Agendar() {
  return (
    <section id="agendar" className="on-ink" style={{ background: "var(--ink)", color: "var(--bone)" }}>
      <div style={{ maxWidth: 1280, margin: "0 auto", padding: "104px 32px", position: "relative" }}>
        <div style={{
          position: "absolute", top: 0, right: 0, width: 540, height: 380,
          background: "radial-gradient(50% 50% at 70% 50%, rgba(184,136,74,0.22), transparent 70%)", pointerEvents: "none"
        }} />
        <div style={{ position: "relative", maxWidth: 880, marginBottom: 48 }}>
          <Eyebrow tone="dark">Hablemos</Eyebrow>
          <h2 className="display-m" style={{ margin: "16px 0 0", color: "var(--bone)" }}>
            Una conversación honesta sobre tus obras.
            <span style={{ color: "var(--steel-2)" }}> Evaluamos juntos si encaja contigo, sin compromiso.</span>
          </h2>
        </div>

        <div className="grid-2-md" style={{ position: "relative", display: "grid", gridTemplateColumns: "0.85fr 1.15fr", gap: 20, alignItems: "stretch" }}>
          <ValueCard />
          <AgendarForm />
        </div>
      </div>
    </section>
  );
}

function ValueCard() {
  return (
    <div style={{
      background: "var(--ink-2)", border: "1px solid var(--ink-3)", borderRadius: "var(--r-3)",
      padding: 32, display: "flex", flexDirection: "column", position: "relative", overflow: "hidden"
    }}>
      <div style={{
        position: "absolute", top: -80, right: -80, width: 280, height: 280,
        background: "radial-gradient(50% 50% at 50% 50%, rgba(184,136,74,0.42), transparent 70%)", pointerEvents: "none"
      }} />
      <div style={{ position: "relative", zIndex: 1, display: "flex", alignItems: "center", gap: 12 }}>
        <TriazTile size={42} bg="var(--bone)" fg="var(--ink)" radius={4} />
        <TriazWordmark height={18} fill="var(--bone)" />
      </div>
      <h3 style={{ position: "relative", zIndex: 1, margin: "28px 0 16px", fontSize: 22, fontWeight: 500, color: "var(--bone)", letterSpacing: "-0.018em", lineHeight: 1.25 }}>
        Qué te llevas <span style={{ color: "var(--copper)" }}>de la primera conversación:</span>
      </h3>
      <ul style={{ position: "relative", zIndex: 1, listStyle: "none", padding: 0, margin: "0 0 32px", display: "grid", gap: 14 }}>
        {[
          "Dónde estás perdiendo dinero y tiempo en tus obras",
          "Por qué proceso conviene empezar en tu caso",
          "Qué agentes encajan con tu operativa real",
          "Una estimación honesta de encaje — o un no claro"
        ].map((t) => (
          <li key={t} style={{ display: "flex", alignItems: "flex-start", gap: 12, fontSize: 14.5, color: "var(--bone)", lineHeight: 1.5 }}>
            <span style={{ width: 22, height: 22, borderRadius: 2, background: "rgba(184,136,74,0.22)", display: "inline-flex", alignItems: "center", justifyContent: "center", flexShrink: 0, marginTop: 1 }}>
              <Icon name="check" size={12} color="var(--copper)" />
            </span>
            {t}
          </li>
        ))}
      </ul>
      <div style={{ position: "relative", zIndex: 1, marginTop: "auto", paddingTop: 22, borderTop: "1px solid var(--ink-3)", display: "flex", alignItems: "center", gap: 10 }}>
        <Icon name="clock" size={15} color="var(--copper)" />
        <span className="mono" style={{ fontSize: 11, color: "var(--steel-2)", letterSpacing: "0.04em" }}>
          30 minutos · sin compromiso · contigo, no con un comercial
        </span>
      </div>
    </div>
  );
}

function AgendarForm() {
  const sizes = [
    { label: "< 5", value: "1-4" },
    { label: "5-11", value: "5-11" },
    { label: "11-50", value: "11-50" },
    { label: "51-200", value: "51-200" },
    { label: "> 200", value: "201-500" }
  ];
  const [sizeIdx, setSizeIdx] = React.useState(null);
  const [form, setForm] = React.useState({ firstname: "", lastname: "", company: "", jobtitle: "", email: "", dial: "ES +34", phone: "" });
  const [status, setStatus] = React.useState("idle");
  const [errorMsg, setErrorMsg] = React.useState("");
  const set = (key) => (e) => setForm((f) => ({ ...f, [key]: e.target.value }));

  async function handleSubmit(e) {
    e.preventDefault();
    if (status === "submitting") return;
    setStatus("submitting"); setErrorMsg("");
    const dialCode = (form.dial.match(/\+\d+/) || [""])[0];
    const fullPhone = [dialCode, form.phone.trim()].filter(Boolean).join(" ");
    const sizeValue = sizeIdx !== null ? sizes[sizeIdx].value : "";
    const fields = [
      { name: "firstname", value: form.firstname.trim() },
      { name: "lastname", value: form.lastname.trim() },
      { name: "company", value: form.company.trim() },
      { name: "jobtitle", value: form.jobtitle.trim() },
      { name: "email", value: form.email.trim() },
      { name: "phone", value: fullPhone },
      { name: "numemployees", value: sizeValue }
    ].filter((f) => f.value !== "");
    const payload = { fields, context: { pageUri: typeof window !== "undefined" ? window.location.href : "", pageName: "Triaz — Construcción" } };
    try {
      const res = await fetch(HS_ENDPOINT, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) });
      if (res.ok) { setStatus("success"); }
      else {
        let detail = "";
        try { const j = await res.json(); detail = (j.errors && j.errors[0] && (j.errors[0].message || j.errors[0].errorType)) || j.message || ""; } catch (_) {}
        setStatus("error"); setErrorMsg(detail || "No se pudo enviar. Inténtalo de nuevo en unos minutos.");
      }
    } catch (err) {
      setStatus("error"); setErrorMsg("No hay conexión con el servidor. Revisa tu red e inténtalo de nuevo.");
    }
  }

  if (status === "success") {
    return (
      <div style={{ background: "var(--bone)", border: "1px solid var(--line-light)", borderRadius: "var(--r-3)", padding: 32, color: "var(--ink)", minHeight: 440, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", textAlign: "center" }}>
        <span style={{ width: 54, height: 54, borderRadius: 4, background: "var(--copper)", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 22 }}>
          <Icon name="check" size={26} color="var(--ink)" />
        </span>
        <h3 style={{ fontSize: 22, fontWeight: 500, letterSpacing: "-0.018em", margin: "0 0 10px" }}>¡Gracias{form.firstname ? `, ${form.firstname}` : ""}!</h3>
        <p style={{ margin: "0 0 24px", fontSize: 15, color: "var(--steel)", maxWidth: 360, lineHeight: 1.55 }}>
          Hemos recibido tu solicitud. Un especialista de Triaz se pondrá en contacto contigo para agendar la conversación.
        </p>
        <button type="button" className="btn btn-secondary" onClick={() => { setStatus("idle"); setForm({ firstname: "", lastname: "", company: "", jobtitle: "", email: "", dial: "ES +34", phone: "" }); setSizeIdx(null); }}>
          Enviar otra solicitud
        </button>
      </div>
    );
  }

  const submitting = status === "submitting";
  return (
    <form onSubmit={handleSubmit} style={{ background: "var(--bone)", border: "1px solid var(--line-light)", borderRadius: "var(--r-3)", padding: 32, color: "var(--ink)" }}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
        <CField label="Nombre" placeholder="Juan" value={form.firstname} onChange={set("firstname")} required />
        <CField label="Apellidos" placeholder="García" value={form.lastname} onChange={set("lastname")} />
        <CField label="Empresa" placeholder="Constructora S.L." value={form.company} onChange={set("company")} />
        <CField label="Cargo" placeholder="Director de operaciones" value={form.jobtitle} onChange={set("jobtitle")} />
        <CField label="Email" placeholder="juan@empresa.es" type="email" value={form.email} onChange={set("email")} required />
        <CPhone dial={form.dial} phone={form.phone} onDial={set("dial")} onPhone={set("phone")} />
      </div>

      <div style={{ marginTop: 24 }}>
        <CLabel>Número de empleados</CLabel>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 10 }}>
          {sizes.map((s, idx) => (
            <button key={s.label} type="button"
              className={"size-pill" + (sizeIdx === idx ? " active" : "")}
              onClick={() => setSizeIdx(idx)}>
              {s.label}
            </button>
          ))}
        </div>
      </div>

      {status === "error" &&
        <div style={{ marginTop: 22, padding: "12px 14px", background: "rgba(154,58,46,0.08)", border: "1px solid rgba(154,58,46,0.32)", borderRadius: "var(--r-2)", display: "flex", alignItems: "flex-start", gap: 10, fontSize: 13, lineHeight: 1.5, color: "#7E2D23" }}>
          <Icon name="circle-dashed" size={15} color="#9A3A2E" style={{ marginTop: 1, flexShrink: 0 }} />
          {errorMsg}
        </div>}

      <button type="submit" className="btn btn-primary" disabled={submitting}
        style={{ width: "100%", height: 54, marginTop: status === "error" ? 16 : 28, fontSize: 15, fontWeight: 500, background: "var(--ink)", opacity: submitting ? 0.7 : 1, cursor: submitting ? "default" : "pointer" }}>
        {submitting ? "Enviando…" : "Agendar conversación"}
        {!submitting && <Icon name="arrow-right" size={15} />}
      </button>

      <div style={{ marginTop: 14, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--steel)", letterSpacing: "0.04em", display: "flex", alignItems: "center", gap: 8, justifyContent: "center" }}>
        <Icon name="lock" size={11} color="var(--steel)" />
        Tus datos solo se usan para responderte. Sin spam, sin venta a terceros.
      </div>
    </form>
  );
}

function CField({ label, type = "text", placeholder, value, onChange, required }) {
  return (
    <div>
      <CLabel>{label}</CLabel>
      <input className="input" type={type} placeholder={placeholder} value={value} onChange={onChange} required={required} />
    </div>
  );
}

function CPhone({ dial, phone, onDial, onPhone }) {
  return (
    <div>
      <CLabel>Teléfono</CLabel>
      <div style={{ display: "flex", gap: 8 }}>
        <select className="input" style={{ flex: "0 0 100px", paddingLeft: 10, paddingRight: 6 }} value={dial} onChange={onDial}>
          <option>ES +34</option><option>FR +33</option><option>PT +351</option><option>UK +44</option><option>DE +49</option><option>IT +39</option>
        </select>
        <input className="input" type="tel" placeholder="Tu número de teléfono" style={{ flex: 1 }} value={phone} onChange={onPhone} />
      </div>
    </div>
  );
}

function CLabel({ children }) {
  return (
    <label className="mono" style={{ display: "block", fontSize: 10.5, fontWeight: 500, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--steel)", marginBottom: 8 }}>
      {children}
    </label>
  );
}

/* ============================================================ */
/*  FOOTER (con Sectores)                                        */
/* ============================================================ */

function Footer() {
  return (
    <footer style={{ background: "var(--bone-2)", borderTop: "1px solid var(--line-light)" }}>
      <div style={{ maxWidth: 1280, margin: "0 auto", padding: "56px 32px 32px" }}>
        <div className="grid-4-md" style={{ display: "grid", gridTemplateColumns: "1.7fr 1fr 1fr 1fr", gap: 40, marginBottom: 48 }}>
          <div>
            <div style={{ marginBottom: 16 }}><TriazWordmark height={22} fill="var(--ink)" /></div>
            <p style={{ margin: 0, fontSize: 13.5, color: "var(--steel)", maxWidth: 360, lineHeight: 1.6 }}>
              El departamento externo de datos, automatización e IA para empresas que trabajan por proyectos.
            </p>
          </div>

          {/* Sectores */}
          <div>
            <div className="mono" style={{ fontSize: 10.5, color: "var(--steel)", letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: 16 }}>Sectores</div>
            <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "grid", gap: 10 }}>
              <li>
                <a href="/construccion" style={{ fontSize: 14, color: "var(--ink)", fontWeight: 500, display: "inline-flex", alignItems: "center", gap: 8 }}>
                  Construcción
                  <span className="mono" style={{ fontSize: 9, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--copper)", border: "1px solid var(--copper)", borderRadius: 2, padding: "1px 5px" }}>aquí</span>
                </a>
              </li>
              {["Ingeniería", "Instalaciones", "Industria"].map((s) => (
                <li key={s} style={{ fontSize: 14, color: "var(--steel-2)", display: "flex", alignItems: "center", gap: 8 }}>
                  {s}
                  <span className="mono" style={{ fontSize: 9, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--steel)", border: "1px solid var(--line-light)", borderRadius: 2, padding: "1px 5px" }}>pronto</span>
                </li>
              ))}
            </ul>
          </div>

          {[
            { h: "Producto", l: ["Plataforma", "Agentes", "Casos de uso"] },
            { h: "Empresa", l: ["Sobre Triaz", "Contacto", "LinkedIn", "Instagram"] }
          ].map((col) => (
            <div key={col.h}>
              <div className="mono" style={{ fontSize: 10.5, color: "var(--steel)", letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: 16 }}>{col.h}</div>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "grid", gap: 10 }}>
                {col.l.map((a) => (
                  <li key={a}>
                    <a href={a === "LinkedIn" ? "https://www.linkedin.com/company/triaz" : a === "Instagram" ? "https://www.instagram.com/triaz.io/" : a === "Contacto" ? "#agendar" : a === "Plataforma" || a === "Agentes" || a === "Casos de uso" ? "/" : "#"}
                      target={(a === "LinkedIn" || a === "Instagram") ? "_blank" : undefined}
                      rel={(a === "LinkedIn" || a === "Instagram") ? "noopener noreferrer" : undefined}
                      style={{ fontSize: 14, color: "var(--ink)" }}>{a}</a>
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>
        <div style={{ paddingTop: 22, borderTop: "1px solid var(--line-light)", display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 16, fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--steel)", letterSpacing: "0.05em", textTransform: "uppercase" }}>
          <span>© 2026 Triaz · Sevilla</span>
          <div style={{ display: "flex", gap: 28 }}>
            <a href="#">Aviso legal</a><a href="#">Privacidad</a><a href="#">Cookies</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

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