/* global React */
const { useState: useStateForm, useEffect: useEffectForm } = React;

const WHATSAPP_URL = "https://api.whatsapp.com/message/L7NMUKPTEBENE1?autoload=1&app_absent=0&utm_source=ig";
const INSTAGRAM_URL = "https://www.instagram.com/assessoriamave/";

window.MAVE_LINKS = { WHATSAPP_URL, INSTAGRAM_URL };

function DiagnosticForm({ open, onClose }) {
  const [step, setStep] = useStateForm(1);
  const [submitted, setSubmitted] = useStateForm(false);
  const [data, setData] = useStateForm({
    name: "", whatsapp: "", email: "",
    clinic: "", role: "",
    revenue: "", challenge: "",
  });

  useEffectForm(() => {
    if (open) {
      document.body.style.overflow = "hidden";
      setStep(1);
      setSubmitted(false);
    } else {
      document.body.style.overflow = "";
    }
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  useEffectForm(() => {
    const onKey = (e) => { if (e.key === "Escape" && open) onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  if (!open) return null;

  const update = (k) => (e) => setData({ ...data, [k]: e.target.value });

  const canStep1 = data.name.trim() && data.whatsapp.trim() && data.email.trim();
  const canStep2 = data.clinic.trim() && data.role.trim();
  const canSubmit = data.revenue && data.challenge.trim();

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!canSubmit) return;
    // Send to WhatsApp with prefilled message
    const msg = encodeURIComponent(
      `Olá, MaveUp! Quero solicitar um diagnóstico estratégico.\n\n` +
      `Nome: ${data.name}\n` +
      `WhatsApp: ${data.whatsapp}\n` +
      `E-mail: ${data.email}\n` +
      `Clínica: ${data.clinic}\n` +
      `Cargo: ${data.role}\n` +
      `Faturamento: ${data.revenue}\n` +
      `Maior desafio: ${data.challenge}`
    );
    setSubmitted(true);
    // Open WhatsApp in new tab after short delay
    setTimeout(() => {
      window.open(`${WHATSAPP_URL}&text=${msg}`, "_blank");
    }, 600);
  };

  const overlayStyle = {
    position: "fixed", inset: 0, zIndex: 100,
    background: "rgba(11,11,14,0.72)",
    backdropFilter: "blur(8px)",
    WebkitBackdropFilter: "blur(8px)",
    display: "flex", alignItems: "center", justifyContent: "center",
    padding: 24,
    animation: "fadeIn 240ms cubic-bezier(0.2,0,0,1)",
  };

  const modalStyle = {
    background: "#fff",
    borderRadius: 24,
    width: "100%",
    maxWidth: 720,
    maxHeight: "92vh",
    overflow: "hidden",
    display: "flex", flexDirection: "column",
    boxShadow: "0 32px 80px rgba(0,0,0,0.45)",
    animation: "slideUp 320ms cubic-bezier(0.2,0,0,1)",
    position: "relative",
  };

  const inputStyle = {
    width: "100%",
    padding: "14px 16px",
    borderRadius: 10,
    border: "1px solid var(--border-default)",
    background: "#fff",
    fontFamily: "var(--font-body)",
    fontSize: 15,
    color: "var(--fg-primary)",
    outline: "none",
    transition: "border-color 200ms, box-shadow 200ms",
  };

  const labelStyle = {
    display: "block",
    fontSize: 12,
    letterSpacing: "0.08em",
    textTransform: "uppercase",
    color: "var(--fg-tertiary)",
    fontWeight: 500,
    marginBottom: 8,
  };

  return (
    <div style={overlayStyle} onClick={onClose}>
      <div style={modalStyle} onClick={(e) => e.stopPropagation()}>
        {/* Header */}
        <div style={{
          background: "var(--ink-900)",
          color: "#fff",
          padding: "32px 36px 28px",
          position: "relative",
          overflow: "hidden",
        }}>
          <div aria-hidden="true" style={{
            position: "absolute", top: "-40%", right: "-10%",
            width: 400, height: 400,
            background: "radial-gradient(circle, rgba(64,13,166,0.55), transparent 60%)",
            filter: "blur(40px)", pointerEvents: "none",
          }} />
          <div style={{ position: "relative", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16 }}>
            <div>
              <div style={{ fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--brand-violet-300)", marginBottom: 8, display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ width: 6, height: 6, borderRadius: 999, background: "var(--brand-violet-300)" }} />
                {submitted ? "Recebido" : "Diagnóstico estratégico"}
              </div>
              <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 24, lineHeight: 1.15, letterSpacing: "-0.01em" }}>
                {submitted ? "Tudo certo. Em instantes você fala conosco." : "Vamos identificar os gargalos da sua clínica."}
              </div>
            </div>
            <button
              onClick={onClose}
              aria-label="Fechar"
              style={{
                width: 40, height: 40, borderRadius: 999,
                background: "rgba(255,255,255,0.08)",
                border: "1px solid rgba(255,255,255,0.15)",
                color: "#fff", cursor: "pointer", flexShrink: 0,
                display: "inline-flex", alignItems: "center", justifyContent: "center",
              }}
            >
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
            </button>
          </div>

          {/* Steps */}
          {!submitted && (
            <div style={{ marginTop: 24, display: "flex", gap: 8 }}>
              {[1, 2, 3].map((s) => (
                <div key={s} style={{
                  flex: 1, height: 3, borderRadius: 99,
                  background: step >= s ? "var(--brand-violet)" : "rgba(255,255,255,0.15)",
                  transition: "background 240ms",
                }} />
              ))}
            </div>
          )}
        </div>

        {/* Body */}
        <div style={{ padding: 36, overflowY: "auto", flex: 1 }}>
          {submitted ? (
            <div style={{ textAlign: "center", padding: "20px 0 12px" }}>
              <div style={{
                width: 72, height: 72, borderRadius: 999,
                background: "var(--brand-violet-50)",
                color: "var(--brand-violet)",
                display: "inline-flex", alignItems: "center", justifyContent: "center",
                marginBottom: 20,
              }}>
                <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
              </div>
              <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 24, lineHeight: 1.2, letterSpacing: "-0.01em", marginBottom: 12 }}>
                Recebemos suas informações.
              </h3>
              <p style={{ color: "var(--fg-secondary)", fontSize: 16, lineHeight: 1.55, maxWidth: 440, margin: "0 auto 28px" }}>
                Estamos te direcionando para o WhatsApp do nosso time. Se a janela não abrir, clique abaixo.
              </p>
              <a
                href={`${WHATSAPP_URL}`}
                target="_blank"
                rel="noopener noreferrer"
                className="btn btn-primary"
              >
                Abrir conversa no WhatsApp
                <span className="arrow"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg></span>
              </a>
            </div>
          ) : (
            <form onSubmit={handleSubmit}>
              {step === 1 && (
                <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
                  <div>
                    <label style={labelStyle}>Nome completo</label>
                    <input style={inputStyle} type="text" required value={data.name} onChange={update("name")} placeholder="Como podemos te chamar?" />
                  </div>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }} className="form-row">
                    <div>
                      <label style={labelStyle}>WhatsApp</label>
                      <input style={inputStyle} type="tel" required value={data.whatsapp} onChange={update("whatsapp")} placeholder="(11) 99999-9999" />
                    </div>
                    <div>
                      <label style={labelStyle}>E-mail</label>
                      <input style={inputStyle} type="email" required value={data.email} onChange={update("email")} placeholder="seu@email.com" />
                    </div>
                  </div>
                </div>
              )}

              {step === 2 && (
                <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
                  <div>
                    <label style={labelStyle}>Nome da clínica</label>
                    <input style={inputStyle} type="text" required value={data.clinic} onChange={update("clinic")} placeholder="Ex.: Clínica Estética Premium" />
                  </div>
                  <div>
                    <label style={labelStyle}>Seu papel na clínica</label>
                    <select style={{ ...inputStyle, appearance: "none", paddingRight: 36, backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%236b6b78' stroke-width='2' stroke-linecap='round'><polyline points='6 9 12 15 18 9'/></svg>\")", backgroundRepeat: "no-repeat", backgroundPosition: "right 14px center" }} required value={data.role} onChange={update("role")}>
                      <option value="">Selecione...</option>
                      <option value="Dono(a) / Sócio(a)">Dono(a) / Sócio(a)</option>
                      <option value="Médico(a) / Doutor(a)">Médico(a) / Doutor(a)</option>
                      <option value="Gestor(a)">Gestor(a)</option>
                      <option value="Outro">Outro</option>
                    </select>
                  </div>
                </div>
              )}

              {step === 3 && (
                <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
                  <div>
                    <label style={labelStyle}>Faturamento médio mensal</label>
                    <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 8 }}>
                      {["Até R$ 30k", "R$ 30k–80k", "R$ 80k–200k", "Acima de R$ 200k"].map((opt) => (
                        <label key={opt} style={{
                          padding: "14px 16px",
                          borderRadius: 10,
                          border: `1px solid ${data.revenue === opt ? "var(--brand-violet)" : "var(--border-default)"}`,
                          background: data.revenue === opt ? "var(--brand-violet-50)" : "#fff",
                          color: data.revenue === opt ? "var(--brand-violet)" : "var(--fg-primary)",
                          fontWeight: data.revenue === opt ? 600 : 500,
                          fontSize: 14,
                          cursor: "pointer",
                          transition: "all 200ms",
                          display: "flex", alignItems: "center", gap: 10,
                        }}>
                          <input type="radio" name="revenue" value={opt} checked={data.revenue === opt} onChange={update("revenue")} style={{ display: "none" }} />
                          <span style={{
                            width: 16, height: 16, borderRadius: 999,
                            border: `1px solid ${data.revenue === opt ? "var(--brand-violet)" : "var(--ink-300)"}`,
                            background: data.revenue === opt ? "var(--brand-violet)" : "#fff",
                            display: "inline-flex", alignItems: "center", justifyContent: "center",
                            flexShrink: 0,
                          }}>
                            {data.revenue === opt && <span style={{ width: 6, height: 6, borderRadius: 999, background: "#fff" }} />}
                          </span>
                          {opt}
                        </label>
                      ))}
                    </div>
                  </div>
                  <div>
                    <label style={labelStyle}>Qual o maior desafio hoje?</label>
                    <textarea
                      style={{ ...inputStyle, resize: "vertical", minHeight: 110, fontFamily: "var(--font-body)" }}
                      required
                      value={data.challenge}
                      onChange={update("challenge")}
                      placeholder="Conte rapidamente o que está travando o crescimento da sua clínica."
                    />
                  </div>
                </div>
              )}

              {/* Footer */}
              <div style={{
                marginTop: 28,
                display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12,
              }}>
                <button
                  type="button"
                  onClick={() => step > 1 ? setStep(step - 1) : onClose()}
                  className="btn btn-ghost-light"
                  style={{ padding: "12px 18px", fontSize: 14 }}
                >
                  {step > 1 ? "Voltar" : "Cancelar"}
                </button>
                {step < 3 ? (
                  <button
                    type="button"
                    onClick={() => setStep(step + 1)}
                    disabled={(step === 1 && !canStep1) || (step === 2 && !canStep2)}
                    className="btn btn-primary"
                    style={{
                      padding: "12px 22px", fontSize: 14,
                      opacity: ((step === 1 && !canStep1) || (step === 2 && !canStep2)) ? 0.4 : 1,
                      cursor: ((step === 1 && !canStep1) || (step === 2 && !canStep2)) ? "not-allowed" : "pointer",
                    }}
                  >
                    Continuar
                    <span className="arrow"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg></span>
                  </button>
                ) : (
                  <button
                    type="submit"
                    disabled={!canSubmit}
                    className="btn btn-primary"
                    style={{
                      padding: "12px 22px", fontSize: 14,
                      opacity: !canSubmit ? 0.4 : 1,
                      cursor: !canSubmit ? "not-allowed" : "pointer",
                    }}
                  >
                    Enviar e abrir WhatsApp
                    <span className="arrow"><svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51l-.57-.01c-.198 0-.52.074-.792.372s-1.04 1.016-1.04 2.479 1.065 2.876 1.213 3.074c.149.198 2.096 3.2 5.077 4.487.71.306 1.263.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 0 1-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 0 1-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 0 1 2.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0 0 12.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 0 0 5.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893A11.821 11.821 0 0 0 20.464 3.488"/></svg></span>
                  </button>
                )}
              </div>
              <style>{`
                input:focus, select:focus, textarea:focus {
                  border-color: var(--brand-violet) !important;
                  box-shadow: 0 0 0 4px rgba(64,13,166,0.14) !important;
                }
                @media (max-width: 560px) {
                  .form-row { grid-template-columns: 1fr !important; }
                }
              `}</style>
            </form>
          )}
        </div>
      </div>
      <style>{`
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
        @keyframes slideUp {
          from { opacity: 0; transform: translateY(24px) scale(0.98); }
          to { opacity: 1; transform: translateY(0) scale(1); }
        }
      `}</style>
    </div>
  );
}

function WhatsAppFloat() {
  const [hover, setHover] = useStateForm(false);
  return (
    <a
      href={WHATSAPP_URL}
      target="_blank"
      rel="noopener noreferrer"
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        position: "fixed",
        bottom: 24, right: 24,
        zIndex: 60,
        display: "inline-flex", alignItems: "center", gap: 12,
        padding: hover ? "14px 22px 14px 14px" : "14px",
        borderRadius: 999,
        background: "#25D366",
        color: "#fff",
        textDecoration: "none",
        fontFamily: "var(--font-body)",
        fontWeight: 600,
        fontSize: 14,
        boxShadow: "0 12px 32px rgba(37,211,102,0.4), 0 4px 12px rgba(0,0,0,0.2)",
        transition: "padding 240ms cubic-bezier(0.2,0,0,1), transform 240ms",
        transform: hover ? "translateY(-2px)" : "translateY(0)",
      }}
      aria-label="Falar no WhatsApp"
    >
      <span style={{
        width: 32, height: 32,
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        flexShrink: 0,
      }}>
        <svg width="22" height="22" viewBox="0 0 24 24" fill="#fff">
          <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51l-.57-.01c-.198 0-.52.074-.792.372s-1.04 1.016-1.04 2.479 1.065 2.876 1.213 3.074c.149.198 2.096 3.2 5.077 4.487.71.306 1.263.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 0 1-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 0 1-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 0 1 2.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0 0 12.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 0 0 5.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893A11.821 11.821 0 0 0 20.464 3.488"/>
        </svg>
      </span>
      {hover && (
        <span style={{ whiteSpace: "nowrap", paddingRight: 4 }}>Falar com o time</span>
      )}
    </a>
  );
}

window.DiagnosticForm = DiagnosticForm;
window.WhatsAppFloat = WhatsAppFloat;
