const formStyles = {
  backdrop: {
    position: "fixed", inset: 0, zIndex: 80,
    background: "rgba(30, 42, 27, 0.5)",
    backdropFilter: "blur(8px)",
    WebkitBackdropFilter: "blur(8px)",
    display: "grid", placeItems: "center",
    padding: 20,
    animation: "fadeIn 0.25s ease"
  },
  modal: {
    background: "var(--cream-50)",
    borderRadius: 24,
    maxWidth: 620, width: "100%",
    maxHeight: "90vh", overflow: "hidden",
    display: "flex", flexDirection: "column",
    boxShadow: "0 40px 80px -20px rgba(0,0,0,0.4)",
    animation: "slideUp 0.3s cubic-bezier(.2,.8,.2,1)"
  },
  header: {
    padding: "24px 28px",
    borderBottom: "1px solid rgba(42,37,32,0.08)",
    display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16
  },
  progressBar: {
    height: 4, background: "rgba(42,37,32,0.08)", borderRadius: 999, overflow: "hidden",
    flex: 1, marginRight: 16
  },
  progressFill: { height: "100%", background: "var(--sage-500)", transition: "width 0.4s" },
  close: {
    width: 36, height: 36, borderRadius: "50%",
    background: "var(--cream-100)", display: "grid", placeItems: "center",
    color: "var(--warm-700)"
  },
  body: { padding: "40px 40px 32px", overflow: "auto", flex: 1 },
  stepLabel: { fontSize: 12, color: "var(--sage-700)", letterSpacing: "0.1em", textTransform: "uppercase", fontWeight: 500, marginBottom: 12 },
  stepTitle: { fontFamily: "'Outfit', sans-serif", fontSize: 32, lineHeight: 1.1, letterSpacing: "-0.02em", fontWeight: 400, marginBottom: 8, textWrap: "balance" },
  stepSub: { fontSize: 15, color: "var(--warm-500)", marginBottom: 28, lineHeight: 1.5 },
  optGrid: { display: "grid", gap: 10 },
  opt: {
    padding: "16px 18px",
    border: "1.5px solid rgba(42,37,32,0.12)",
    borderRadius: 14, background: "var(--cream-50)",
    display: "flex", alignItems: "center", gap: 14,
    cursor: "pointer", textAlign: "left", width: "100%",
    transition: "border 0.15s, background 0.15s, transform 0.15s",
    fontSize: 15
  },
  optSelected: { borderColor: "var(--sage-600)", background: "var(--sage-50)" },
  optMark: {
    width: 22, height: 22, borderRadius: 6,
    border: "1.5px solid rgba(42,37,32,0.2)",
    display: "grid", placeItems: "center", flexShrink: 0,
    transition: "all 0.15s"
  },
  optMarkActive: { background: "var(--sage-600)", borderColor: "var(--sage-600)", color: "white" },
  input: {
    width: "100%", padding: "14px 16px",
    border: "1.5px solid rgba(42,37,32,0.12)",
    borderRadius: 12, fontSize: 16,
    background: "white", color: "var(--warm-900)",
    outline: "none", transition: "border 0.15s"
  },
  footer: {
    padding: "20px 28px",
    borderTop: "1px solid rgba(42,37,32,0.08)",
    display: "flex", justifyContent: "space-between", alignItems: "center", gap: 16
  },
  backBtn: {
    padding: "12px 18px", borderRadius: 10,
    color: "var(--warm-500)", fontSize: 14, fontWeight: 500
  },
  nextBtn: {
    display: "inline-flex", alignItems: "center", gap: 8,
    padding: "14px 22px", borderRadius: 999,
    background: "var(--warm-900)", color: "var(--cream-50)",
    fontSize: 15, fontWeight: 500,
    transition: "background 0.2s, opacity 0.2s"
  },
  nextBtnDisabled: { opacity: 0.4, cursor: "not-allowed" },
  success: { textAlign: "center", padding: "20px 0" },
  successIcon: {
    width: 72, height: 72, borderRadius: "50%",
    background: "var(--sage-100)", color: "var(--sage-700)",
    display: "grid", placeItems: "center", margin: "0 auto 24px"
  }
};

const stepsConfig = [
  {
    key: null, type: "intro", label: "Início",
    title: "Fala! Vamos entender seu objetivo?",
    sub: "Responda algumas perguntas rápidas para agendar sua consulta com a Nutricionista Diana Vicente."
  },
  {
    key: "name", type: "text", label: "Nome",
    title: "Qual é o seu nome?",
    placeholder: "Seu nome completo"
  },
  {
    key: "phone", type: "tel", label: "WhatsApp",
    title: "Qual é o seu WhatsApp?",
    placeholder: "(48) 99999-9999"
  },
  {
    key: "city", type: "text", label: "Cidade",
    title: "Você mora em qual cidade?",
    placeholder: "Sua cidade e estado"
  },
  {
    key: "modality", type: "single", label: "Atendimento",
    title: "Você prefere atendimento online ou presencial em Florianópolis SC?",
    options: [
      { v: "online", t: "Online" },
      { v: "presencial", t: "Presencial em Florianópolis SC" },
      { v: "naosei", t: "Ainda não sei" }
    ]
  },
  {
    key: "goal", type: "single", label: "Objetivo",
    title: "Qual é o seu principal objetivo hoje?",
    options: [
      { v: "emagrecer", t: "Emagrecer" },
      { v: "definir", t: "Definir o corpo" },
      { v: "massa", t: "Ganhar massa muscular" },
      { v: "gordura", t: "Reduzir gordura" },
      { v: "performance", t: "Melhorar performance nos treinos" },
      { v: "alimentacao", t: "Organizar minha alimentação" }
    ]
  },
  {
    key: "trains", type: "single", label: "Treino atual",
    title: "Você treina atualmente?",
    options: [
      { v: "sim_freq", t: "Sim, treino com frequência" },
      { v: "sim_irreg", t: "Sim, mas sem constância" },
      { v: "parada", t: "Estou parada, mas quero voltar" },
      { v: "nao", t: "Ainda não treino" }
    ]
  },
  {
    key: "trainTime", type: "single", label: "Experiência",
    title: "Há quanto tempo você treina?",
    options: [
      { v: "menos3", t: "Menos de 3 meses" },
      { v: "3a6", t: "De 3 a 6 meses" },
      { v: "6a12", t: "De 6 meses a 1 ano" },
      { v: "mais1", t: "Mais de 1 ano" },
      { v: "naotreino", t: "Não treino atualmente" }
    ]
  },
  {
    key: "challenge", type: "multi", label: "Dificuldade",
    title: "Qual é sua maior dificuldade hoje?",
    sub: "Pode marcar mais de uma.",
    options: [
      { v: "naoemagrece", t: "Não consigo emagrecer" },
      { v: "naomassa", t: "Não consigo ganhar massa" },
      { v: "dieta", t: "Tenho dificuldade em seguir dieta" },
      { v: "plato", t: "Meu corpo estacionou" },
      { v: "comer", t: "Não sei o que comer" },
      { v: "ansiedade", t: "Tenho muita ansiedade com comida" }
    ]
  },
  {
    key: "history", type: "single", label: "Histórico",
    title: "Você já fez acompanhamento com nutricionista antes?",
    options: [
      { v: "sim", t: "Sim" },
      { v: "nao", t: "Não" },
      { v: "semresultado", t: "Já fiz, mas não tive o resultado que queria" }
    ]
  },
  {
    key: "message", type: "textarea", label: "Objetivo",
    title: "Conte o que você gostaria de mudar no seu corpo, alimentação ou rotina.",
    sub: "Pode ser curto, o importante é a Diana entender o seu momento.",
    placeholder: "Escreva aqui..."
  }
];

const MultiStepForm = ({ open, onClose, onWhatsApp }) => {
  const [step, setStep] = React.useState(0);
  const [data, setData] = React.useState({});
  const [done, setDone] = React.useState(false);

  React.useEffect(() => {
    if (open) { setStep(0); setData({}); setDone(false); }
  }, [open]);

  if (!open) return null;

  const cfg = stepsConfig[step];
  const total = stepsConfig.length;
  const progress = done ? 100 : ((step) / total) * 100 + (10 / total);

  const canAdvance = () => {
    if (cfg.type === "intro") return true;
    if (cfg.type === "single") return !!data[cfg.key];
    if (cfg.type === "multi") return Array.isArray(data[cfg.key]) && data[cfg.key].length > 0;
    if (cfg.type === "text" || cfg.type === "tel") return !!(data[cfg.key] && data[cfg.key].trim());
    if (cfg.type === "textarea") return !!(data[cfg.key] && data[cfg.key].trim());
    return false;
  };

  const next = () => {
    if (step < total - 1) setStep(step + 1);
    else setDone(true);
  };
  const prev = () => step > 0 && setStep(step - 1);

  const toggle = (key, val, multi) => {
    if (multi) {
      const cur = data[key] || [];
      setData({ ...data, [key]: cur.includes(val) ? cur.filter(v => v !== val) : [...cur, val] });
    } else {
      setData({ ...data, [key]: val });
    }
  };

  const nextLabel = cfg.type === "intro" ? "Começar" : step === total - 1 ? "Enviar" : "Continuar";

  return (
    <div className="form-backdrop" style={formStyles.backdrop} onClick={onClose}>
      <div className="form-modal" style={formStyles.modal} onClick={e => e.stopPropagation()}>
        <div className="form-header" style={formStyles.header}>
          <div style={formStyles.progressBar}>
            <div style={{ ...formStyles.progressFill, width: `${progress}%` }} />
          </div>
          <button style={formStyles.close} onClick={onClose} aria-label="Fechar"><IconClose size={18} /></button>
        </div>

        <div className="form-body" style={formStyles.body}>
          {done ? (
            <div style={formStyles.success}>
              <div style={formStyles.successIcon}><IconCheck size={34} stroke={2} /></div>
              <h3 style={{ ...formStyles.stepTitle, marginBottom: 12 }}>Perfeito, {data.name?.split(" ")[0] || "gatona"}!</h3>
              <p style={{ ...formStyles.stepSub, maxWidth: 420, margin: "0 auto 28px" }}>
                A equipe da Diana vai entrar em contato para orientar o agendamento da sua consulta.
                Se preferir, pode falar diretamente pelo WhatsApp agora.
              </p>
              <div style={{ display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap" }}>
                <button
                  style={{ ...formStyles.nextBtn, background: "#25D366" }}
                  onClick={onWhatsApp}
                >
                  <IconWhatsApp size={18} color="white" />
                  Agendar pelo WhatsApp
                </button>
                <button style={{ ...formStyles.nextBtn, background: "var(--cream-100)", color: "var(--warm-900)" }} onClick={onClose}>
                  Voltar pro site
                </button>
              </div>
            </div>
          ) : (
            <>
              {cfg.type !== "intro" && (
                <div style={formStyles.stepLabel}>Passo {step} de {total - 1} • {cfg.label}</div>
              )}
              <h3 className="form-step-title" style={formStyles.stepTitle}>{cfg.title}</h3>
              {cfg.sub && <p style={formStyles.stepSub}>{cfg.sub}</p>}

              {cfg.type === "intro" ? null : cfg.type === "text" || cfg.type === "tel" ? (
                <input
                  style={formStyles.input}
                  placeholder={cfg.placeholder}
                  type={cfg.type === "tel" ? "tel" : "text"}
                  value={data[cfg.key] || ""}
                  onChange={e => setData({ ...data, [cfg.key]: e.target.value })}
                  onFocus={e => e.target.style.borderColor = "var(--sage-600)"}
                  onBlur={e => e.target.style.borderColor = "rgba(42,37,32,0.12)"}
                  onKeyDown={e => { if (e.key === "Enter" && canAdvance()) next(); }}
                  autoFocus
                />
              ) : cfg.type === "textarea" ? (
                <textarea
                  style={{ ...formStyles.input, minHeight: 120, resize: "vertical" }}
                  placeholder={cfg.placeholder}
                  value={data[cfg.key] || ""}
                  onChange={e => setData({ ...data, [cfg.key]: e.target.value })}
                  onFocus={e => e.target.style.borderColor = "var(--sage-600)"}
                  onBlur={e => e.target.style.borderColor = "rgba(42,37,32,0.12)"}
                  rows={4}
                />
              ) : (
                <div style={formStyles.optGrid}>
                  {cfg.options.map(o => {
                    const selected = cfg.type === "multi"
                      ? (data[cfg.key] || []).includes(o.v)
                      : data[cfg.key] === o.v;
                    return (
                      <button
                        key={o.v}
                        className="form-option"
                        style={{ ...formStyles.opt, ...(selected ? formStyles.optSelected : {}) }}
                        onClick={() => { toggle(cfg.key, o.v, cfg.type === "multi"); if (cfg.type === "single") setTimeout(next, 220); }}
                        onMouseEnter={e => { if (!selected) e.currentTarget.style.borderColor = "var(--sage-400)"; }}
                        onMouseLeave={e => { if (!selected) e.currentTarget.style.borderColor = "rgba(42,37,32,0.12)"; }}
                      >
                        <span style={{ ...formStyles.optMark, ...(selected ? formStyles.optMarkActive : {}), borderRadius: cfg.type === "multi" ? 6 : "50%" }}>
                          {selected && <IconCheck size={14} stroke={3} />}
                        </span>
                        <span style={{ flex: 1 }}>
                          <div style={{ fontWeight: 500, color: "var(--warm-900)" }}>{o.t}</div>
                          {o.d && <div style={{ fontSize: 13, color: "var(--warm-500)", marginTop: 2 }}>{o.d}</div>}
                        </span>
                      </button>
                    );
                  })}
                </div>
              )}
            </>
          )}
        </div>

        {!done && (
          <div className="form-footer" style={formStyles.footer}>
            <button className="form-back-btn" style={{ ...formStyles.backBtn, visibility: step === 0 ? "hidden" : "visible" }} onClick={prev}>
              ← Voltar
            </button>
            <button
              className="form-next-btn"
              style={{ ...formStyles.nextBtn, ...(canAdvance() ? {} : formStyles.nextBtnDisabled) }}
              onClick={() => canAdvance() && next()}
              disabled={!canAdvance()}
            >
              {nextLabel}
              <IconArrowRight size={16} />
            </button>
          </div>
        )}
      </div>

      <style>{`
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
        @keyframes slideUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
        @media (max-width: 560px) {
          .form-backdrop {
            align-items: end !important;
            padding: 0 !important;
          }
          .form-modal {
            width: 100% !important;
            max-height: 92vh !important;
            border-radius: 22px 22px 0 0 !important;
          }
          .form-header {
            padding: 18px 20px !important;
          }
          .form-body {
            padding: 28px 20px 24px !important;
          }
          .form-step-title {
            font-size: 26px !important;
            letter-spacing: 0 !important;
          }
          .form-option {
            min-height: 52px !important;
            padding: 14px 14px !important;
          }
          .form-footer {
            padding: 16px 20px calc(16px + env(safe-area-inset-bottom)) !important;
            gap: 10px !important;
          }
          .form-back-btn,
          .form-next-btn {
            min-height: 48px !important;
          }
          .form-next-btn {
            flex: 1 !important;
            justify-content: center !important;
          }
        }
      `}</style>
    </div>
  );
};

Object.assign(window, { MultiStepForm });
