/* global React */
const { useState: useStateF, useEffect: useEffectF, useRef: useRefF } = React;

function ContactForm({ open, onClose, t }) {
  const ft = t.form;
  const [mounted, setMounted] = useStateF(false);
  const [visible, setVisible] = useStateF(false);
  const [step, setStep] = useStateF(0);
  const [data, setData] = useStateF({
    objetivos: [],
    tamano: "",
    urgencia: "",
    presupuesto: "",
    nombre: "",
    empresa: "",
    email: "",
    telefono: "",
    mensaje: "",
  });
  const [submitted, setSubmitted] = useStateF(false);
  const totalSteps = 3;

  useEffectF(() => {
    if (open) {
      setMounted(true);
      const r1 = requestAnimationFrame(() => {
        const r2 = requestAnimationFrame(() => setVisible(true));
        ContactForm._raf = r2;
      });
      return () => {
        cancelAnimationFrame(r1);
        if (ContactForm._raf) cancelAnimationFrame(ContactForm._raf);
      };
    } else {
      setVisible(false);
      const t = setTimeout(() => { setMounted(false); setStep(0); setSubmitted(false); }, 460);
      return () => clearTimeout(t);
    }
  }, [open]);

  if (!open && !mounted) return null;

  const shown = open && visible;

  const update = (k, v) => setData((d) => ({ ...d, [k]: v }));
  const toggleObjetivo = (id) => setData((d) => ({
    ...d,
    objetivos: d.objetivos.includes(id) ? d.objetivos.filter((x) => x !== id) : [...d.objetivos, id],
  }));

  const canAdvance = () => {
    if (step === 0) return data.objetivos.length > 0 && data.urgencia;
    if (step === 1) return data.tamano && data.presupuesto;
    if (step === 2) return data.nombre.trim() && data.email.trim() && /@.+\./.test(data.email);
    return false;
  };

  const handleSubmit = () => {
    if (!canAdvance()) return;
    setSubmitted(true);
  };

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 35, pointerEvents: open ? "auto" : "none" }}>
      {/* Backdrop */}
      <div
        onClick={onClose}
        style={{
          position: "absolute", inset: 0,
          background: shown ? "rgba(6,6,7,0.65)" : "rgba(6,6,7,0)",
          backdropFilter: `blur(${shown ? 10 : 0}px)`,
          WebkitBackdropFilter: `blur(${shown ? 10 : 0}px)`,
          opacity: shown ? 1 : 0,
          transition: "opacity 480ms cubic-bezier(.2,.7,.25,1), background 480ms cubic-bezier(.2,.7,.25,1), backdrop-filter 480ms cubic-bezier(.2,.7,.25,1), -webkit-backdrop-filter 480ms cubic-bezier(.2,.7,.25,1)",
          willChange: "opacity, backdrop-filter",
        }}
      />
      {/* Form container */}
      <div
        role="dialog"
        aria-modal="true"
        className="elm-form"
        style={{
          position: "absolute",
          top: "50%", left: "50%",
          transform: `translate(-50%, -50%) translateY(${shown ? 0 : 22}px) scale(${shown ? 1 : 0.99})`,
          opacity: shown ? 1 : 0,
          transition: "transform 560ms cubic-bezier(.2,.75,.25,1) 60ms, opacity 440ms cubic-bezier(.2,.7,.25,1) 60ms",
          willChange: "opacity, transform",
          width: "min(820px, 92vw)",
          maxHeight: "88vh",
          background: "linear-gradient(180deg, #0e0e10 0%, #0a0a0b 100%)",
          border: "1px solid var(--line)",
          borderRadius: 20,
          boxShadow: "0 30px 80px rgba(0,0,0,0.6)",
          display: "flex",
          flexDirection: "column",
          overflow: "hidden",
        }}
      >
        {/* Header */}
        <header className="elm-form-header" style={{
          padding: "26px 32px 20px",
          borderBottom: "1px solid var(--line)",
          display: "flex",
          justifyContent: "space-between",
          alignItems: "flex-start",
          background: "rgba(255,255,255,0.01)",
        }}>
          <div>
            <div style={{
              fontFamily: "var(--mono)",
              fontSize: 11,
              letterSpacing: 1.8,
              color: "var(--text-3)",
              textTransform: "uppercase",
              marginBottom: 8,
              display: "flex",
              alignItems: "center",
              gap: 8,
            }}>
              <span style={{ color: "var(--mint)" }}>●</span> Elementa · {ft.title}
            </div>
            <h2 className="elm-form-title" style={{
              fontFamily: "var(--mono)",
              fontWeight: 700,
              fontSize: 24,
              letterSpacing: -0.5,
              margin: 0,
            }}>
              {submitted ? ft.titleSuccess : ft.title}
            </h2>
            {!submitted && (
              <div style={{ color: "var(--text-3)", fontSize: 13, marginTop: 6 }}>
                {ft.stepOf} {step + 1} {ft.of} {totalSteps} · {ft.stepNames[step]}
              </div>
            )}
          </div>
          <button onClick={onClose} aria-label="Cerrar" style={{
            all: "unset",
            cursor: "pointer",
            display: "flex",
            alignItems: "center",
            gap: 10,
            padding: "8px 14px",
            borderRadius: 999,
            border: "1px solid var(--line-2)",
            color: "var(--text-2)",
          }}>
            <span style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--text-3)" }}>{ft.esc || "ESC"}</span>
            <span style={{ fontSize: 22, lineHeight: 1 }}>×</span>
          </button>
        </header>

        {/* Progress bar */}
        {!submitted && (
          <div className="elm-form-progress" style={{ padding: "16px 32px 0", flexShrink: 0 }}>
            <div style={{
              display: "flex", gap: 8,
            }}>
              {[0,1,2].map((i) => (
                <div key={i} style={{
                  flex: 1,
                  height: 3,
                  borderRadius: 999,
                  background: i <= step ? "var(--grad)" : "var(--line-2)",
                  transition: "background 360ms ease",
                }} />
              ))}
            </div>
          </div>
        )}

        {/* Body */}
        <div className="panel-body elm-form-body" style={{
          padding: "26px 32px 28px",
          overflowY: "auto",
          flex: 1,
        }}>
          {submitted ? (
            <SuccessView data={data} onClose={onClose} ft={ft} t={t} />
          ) : step === 0 ? (
            <Step0 data={data} toggleObjetivo={toggleObjetivo} update={update} ft={ft} />
          ) : step === 1 ? (
            <Step1 data={data} update={update} ft={ft} />
          ) : (
            <Step2 data={data} update={update} ft={ft} />
          )}
        </div>

        {/* Footer */}
        {!submitted && (
          <footer className="elm-form-footer" style={{
            padding: "18px 32px",
            borderTop: "1px solid var(--line)",
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            gap: 12,
            background: "rgba(255,255,255,0.015)",
            flexShrink: 0,
          }}>
            <button
              onClick={() => step > 0 ? setStep(step - 1) : onClose()}
              style={{
                all: "unset",
                cursor: "pointer",
                fontSize: 13.5,
                color: "var(--text-2)",
                padding: "10px 18px",
                borderRadius: 999,
                border: "1px solid var(--line-2)",
              }}
            >
              ← {step > 0 ? t.common.back : t.common.cancel}
            </button>

            <div className="elm-form-step-label" style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--text-3)" }}>
              {ft.footerHints[step]}
            </div>

            {step < totalSteps - 1 ? (
              <button
                disabled={!canAdvance()}
                onClick={() => setStep(step + 1)}
                style={{
                  all: "unset",
                  cursor: canAdvance() ? "pointer" : "not-allowed",
                  padding: "11px 22px",
                  borderRadius: 999,
                  background: canAdvance() ? "var(--grad)" : "var(--line-2)",
                  color: canAdvance() ? "#0a0a0a" : "var(--text-3)",
                  fontWeight: 600,
                  fontSize: 13.5,
                  transition: "opacity 200ms",
                  opacity: canAdvance() ? 1 : 0.7,
                }}
              >
                {t.common.next} →
              </button>
            ) : (
              <button
                disabled={!canAdvance()}
                onClick={handleSubmit}
                style={{
                  all: "unset",
                  cursor: canAdvance() ? "pointer" : "not-allowed",
                  padding: "11px 22px",
                  borderRadius: 999,
                  background: canAdvance() ? "var(--grad)" : "var(--line-2)",
                  color: canAdvance() ? "#0a0a0a" : "var(--text-3)",
                  fontWeight: 600,
                  fontSize: 13.5,
                  opacity: canAdvance() ? 1 : 0.7,
                }}
              >
                {t.common.sendRequest} →
              </button>
            )}
          </footer>
        )}
      </div>
    </div>
  );
}

// ───────────────────────────────────────────────────────────────────
function Step0({ data, toggleObjetivo, update, ft }) {
  return (
    <div>
      <div style={formStyle.q}>{ft.q1}</div>
      <div style={formStyle.hint}>{ft.q1Hint}</div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(min(220px, 100%), 1fr))", gap: 10, marginBottom: 30 }}>
        {ft.q1Options.map((o) => {
          const active = data.objetivos.includes(o.id);
          return (
            <button key={o.id} onClick={() => toggleObjetivo(o.id)} style={formStyle.optCard(active)}>
              <div style={{
                ...formStyle.optCheck,
                background: active ? "var(--mint)" : "transparent",
                borderColor: active ? "var(--mint)" : "var(--line-2)",
                color: "#0a0a0a",
              }}>
                {active ? "✓" : ""}
              </div>
              <div style={{ textAlign: "left", flex: 1 }}>
                <div style={formStyle.optLabel}>{o.label}</div>
                <div style={formStyle.optDesc}>{o.desc}</div>
              </div>
            </button>
          );
        })}
      </div>

      <div style={formStyle.q}>{ft.q2}</div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(min(180px, 100%), 1fr))", gap: 10 }}>
        {ft.q2Options.map((u) => {
          const active = data.urgencia === u.id;
          return (
            <button key={u.id} onClick={() => update("urgencia", u.id)} style={formStyle.optCard(active)}>
              <div style={{
                ...formStyle.optRadio,
                borderColor: active ? "var(--mint)" : "var(--line-2)",
              }}>
                {active && <div style={formStyle.optRadioDot} />}
              </div>
              <div style={{ textAlign: "left", flex: 1 }}>
                <div style={formStyle.optLabel}>{u.label}</div>
                <div style={formStyle.optDesc}>{u.desc}</div>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

function Step1({ data, update, ft }) {
  return (
    <div>
      <div style={formStyle.q}>{ft.q3}</div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(min(160px, 100%), 1fr))", gap: 10, marginBottom: 30 }}>
        {ft.q3Options.map((t) => {
          const active = data.tamano === t.id;
          return (
            <button key={t.id} onClick={() => update("tamano", t.id)} style={{
              ...formStyle.optCard(active),
              flexDirection: "column",
              alignItems: "flex-start",
              gap: 8,
              padding: "16px 18px",
              minHeight: 70,
            }}>
              <div style={{
                ...formStyle.optRadio,
                borderColor: active ? "var(--mint)" : "var(--line-2)",
              }}>
                {active && <div style={formStyle.optRadioDot} />}
              </div>
              <div style={formStyle.optLabel}>{t.label}</div>
            </button>
          );
        })}
      </div>

      <div style={formStyle.q}>{ft.q4}</div>
      <div style={formStyle.hint}>{ft.q4Hint}</div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(min(220px, 100%), 1fr))", gap: 10 }}>
        {ft.q4Options.map((p) => {
          const active = data.presupuesto === p.id;
          return (
            <button key={p.id} onClick={() => update("presupuesto", p.id)} style={formStyle.optCard(active)}>
              <div style={{
                ...formStyle.optRadio,
                borderColor: active ? "var(--mint)" : "var(--line-2)",
              }}>
                {active && <div style={formStyle.optRadioDot} />}
              </div>
              <div style={{ textAlign: "left", flex: 1, display: "flex", justifyContent: "space-between", alignItems: "center", gap: 10 }}>
                <div style={formStyle.optLabel}>{p.label}</div>
                <div style={{
                  fontFamily: "var(--mono)",
                  fontSize: 10,
                  letterSpacing: 1.4,
                  textTransform: "uppercase",
                  color: "var(--text-3)",
                  border: "1px solid var(--line-2)",
                  borderRadius: 999,
                  padding: "2px 8px",
                }}>{p.tag}</div>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

function Step2({ data, update, ft }) {
  return (
    <div>
      <div style={formStyle.q}>{ft.yourData}</div>
      <div style={{
        display: "grid",
        gridTemplateColumns: "repeat(auto-fit, minmax(min(260px, 100%), 1fr))",
        gap: 14,
        marginBottom: 18,
      }}>
        <Field label={ft.fNombre} required value={data.nombre} onChange={(v) => update("nombre", v)} placeholder={ft.pNombre} />
        <Field label={ft.fEmpresa} value={data.empresa} onChange={(v) => update("empresa", v)} placeholder={ft.pEmpresa} />
        <Field label={ft.fEmail} required value={data.email} onChange={(v) => update("email", v)} type="email" placeholder="tu@empresa.com" />
        <Field label={ft.fTelefono} value={data.telefono} onChange={(v) => update("telefono", v)} placeholder={ft.pTelefono} />
      </div>

      <Field
        label={ft.fMensaje}
        value={data.mensaje}
        onChange={(v) => update("mensaje", v)}
        textarea
        placeholder={ft.pMensaje}
      />

      <div style={{
        marginTop: 22,
        padding: "16px 20px",
        background: "rgba(179,240,216,0.04)",
        border: "1px solid rgba(179,240,216,0.18)",
        borderRadius: 12,
        fontSize: 13,
        color: "var(--text-2)",
        lineHeight: 1.6,
        display: "flex",
        gap: 12,
      }}>
        <span style={{ color: "var(--mint)", fontSize: 16, marginTop: 1 }}>✓</span>
        <div>
          {ft.slaNote} <strong style={{ color: "var(--text)", fontWeight: 600 }}>{ft.slaBold}</strong> {ft.slaTail}
        </div>
      </div>
    </div>
  );
}

function Field({ label, required, value, onChange, type = "text", placeholder, textarea }) {
  const [focused, setFocused] = useStateF(false);
  const inputStyle = {
    width: "100%",
    background: "var(--bg)",
    border: `1px solid ${focused ? "var(--mint)" : "var(--line-2)"}`,
    borderRadius: 10,
    padding: textarea ? "12px 14px" : "11px 14px",
    color: "var(--text)",
    fontSize: 14,
    fontFamily: "var(--sans)",
    outline: "none",
    transition: "border-color 220ms ease",
    resize: textarea ? "vertical" : "none",
    minHeight: textarea ? 96 : "auto",
    boxSizing: "border-box",
  };
  return (
    <label style={{ display: "block" }}>
      <div style={{
        fontFamily: "var(--mono)",
        fontSize: 10.5,
        letterSpacing: 1.4,
        textTransform: "uppercase",
        color: "var(--text-3)",
        marginBottom: 8,
      }}>
        {label} {required && <span style={{ color: "var(--mint)" }}>*</span>}
      </div>
      {textarea ? (
        <textarea
          value={value}
          onChange={(e) => onChange(e.target.value)}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
          placeholder={placeholder}
          style={inputStyle}
        />
      ) : (
        <input
          type={type}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
          placeholder={placeholder}
          style={inputStyle}
        />
      )}
    </label>
  );
}

function SuccessView({ data, onClose, ft, t }) {
  return (
    <div style={{ textAlign: "center", padding: "20px 20px 32px" }}>
      <div style={{
        width: 64, height: 64,
        margin: "0 auto 22px",
        borderRadius: "50%",
        background: "var(--grad)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        fontSize: 28,
        color: "#0a0a0a",
        fontWeight: 700,
      }}>✓</div>

      <h3 style={{
        fontFamily: "var(--mono)",
        fontWeight: 700,
        fontSize: 22,
        margin: "0 0 12px",
      }}>
        {ft.successTitle(data.nombre.split(" ")[0])}
      </h3>

      <p style={{ color: "var(--text-2)", fontSize: 15, lineHeight: 1.6, maxWidth: 480, margin: "0 auto 28px" }}>
        {ft.successBody}
      </p>

      <div style={{
        display: "inline-block",
        textAlign: "left",
        padding: "18px 22px",
        background: "#0c0c0e",
        border: "1px solid var(--line)",
        borderRadius: 14,
        fontFamily: "var(--mono)",
        fontSize: 12.5,
        color: "var(--text-2)",
        lineHeight: 1.7,
        marginBottom: 28,
      }}>
        <div><span style={{ color: "var(--text-3)" }}>{ft.successRef}</span> ELM-{Math.floor(Math.random() * 9000 + 1000)}</div>
        <div><span style={{ color: "var(--text-3)" }}>{ft.successEmail}</span> {data.email}</div>
        <div><span style={{ color: "var(--text-3)" }}>{ft.successObj}</span> {data.objetivos.join(", ") || "—"}</div>
        <div><span style={{ color: "var(--text-3)" }}>{ft.successSize}</span> {data.tamano || "—"}</div>
      </div>

      <div style={{ display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap" }}>
        <button onClick={onClose} style={{
          all: "unset",
          cursor: "pointer",
          padding: "11px 22px",
          borderRadius: 999,
          background: "var(--grad)",
          color: "#0a0a0a",
          fontWeight: 600,
          fontSize: 13.5,
        }}>{t.common.backToHome}</button>
        <a href="https://wa.me/59897574450" style={{
          padding: "11px 22px",
          borderRadius: 999,
          border: "1px solid var(--line-2)",
          color: "var(--text-2)",
          fontSize: 13.5,
          textDecoration: "none",
          fontFamily: "var(--sans)",
        }}>{t.common.writeWhatsApp}</a>
      </div>
    </div>
  );
}

// ───────────────────────────────────────────────────────────────────
const formStyle = {
  q: {
    fontFamily: "var(--sans)",
    fontWeight: 600,
    fontSize: 16,
    color: "var(--text)",
    marginBottom: 6,
  },
  hint: {
    color: "var(--text-3)",
    fontSize: 13,
    marginBottom: 14,
  },
  optCard: (active) => ({
    all: "unset",
    cursor: "pointer",
    display: "flex",
    gap: 14,
    alignItems: "flex-start",
    padding: "14px 16px",
    borderRadius: 12,
    border: `1px solid ${active ? "rgba(179,240,216,0.4)" : "var(--line-2)"}`,
    background: active ? "rgba(179,240,216,0.05)" : "transparent",
    transition: "background 200ms ease, border-color 200ms ease",
    boxSizing: "border-box",
  }),
  optCheck: {
    width: 20, height: 20,
    borderRadius: 5,
    border: "1.5px solid",
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    fontSize: 13,
    fontWeight: 700,
    flexShrink: 0,
    marginTop: 1,
    transition: "background 200ms, border-color 200ms",
  },
  optRadio: {
    width: 18, height: 18,
    borderRadius: "50%",
    border: "1.5px solid",
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    flexShrink: 0,
    marginTop: 2,
    transition: "border-color 200ms",
  },
  optRadioDot: {
    width: 9, height: 9,
    borderRadius: "50%",
    background: "var(--mint)",
  },
  optLabel: {
    fontSize: 14,
    fontWeight: 500,
    color: "var(--text)",
    lineHeight: 1.3,
    marginBottom: 2,
  },
  optDesc: {
    fontSize: 12.5,
    color: "var(--text-3)",
    lineHeight: 1.45,
  },
};

window.ContactForm = ContactForm;
