/* Website UI kit — Hero
   Full-bleed dark portrait, oversized display headline.
   Primary CTA ("Agendar avaliação") expands into a full-screen booking
   modal (brand info + lead form + submitting/success states).
   On-brand navy/gold, PT-BR, no external deps. */

// WhatsApp da clínica (formato: 55 + DDD + número)
const RM_WA_NUMBER = "5543991311494";
// Link genérico reutilizado pelos botões de WhatsApp do site (float, nav, CTA final)
window.RM_WA_URL = "https://wa.me/" + RM_WA_NUMBER + "?text=" +
  encodeURIComponent("Olá! Gostaria de agendar uma avaliação no consultório do Dr. Renan Moura.");

function useNarrow(maxWidth) {
  const q = "(max-width: " + maxWidth + "px)";
  const [m, setM] = React.useState(() => window.matchMedia(q).matches);
  React.useEffect(() => {
    const mq = window.matchMedia(q);
    const on = (e) => setM(e.matches);
    mq.addEventListener("change", on);
    setM(mq.matches);
    return () => mq.removeEventListener("change", on);
  }, [q]);
  return m;
}

const RM_TREATMENTS = [
  "Rejuvenescimento do olhar",
  "Ortodontia / Alinhadores",
  "Implantes dentários",
  "Harmonização facial",
  "Lentes de contato dental",
  "Odontologia geral",
  "Outro",
];

/* Presets de captação por página.
   Sem preset (home): formulário completo + tela de "recebemos seu contato".
   Com preset (LPs de tráfego pago): só nome + WhatsApp e o envio manda direto
   pro WhatsApp da clínica com a mensagem pronta. */
const RM_LEAD_PRESETS = {
  "rejuvenescimento-do-olhar": {
    treatment: "Rejuvenescimento do olhar",
    title: "Vamos cuidar\ndo seu olhar",
    waMessage: (name) =>
      "Olá, meu nome é " + name + ", tenho interesse no tratamento de Rejuvenescimento do Olhar " +
      "e quero agendar um horário com o Dr. Renan Moura.",
  },
};

function BookingModal({ open, onClose, preset }) {
  const lead = (preset && RM_LEAD_PRESETS[preset]) || null;
  const [render, setRender] = React.useState(false);
  const [shown, setShown] = React.useState(false);
  const [step, setStep] = React.useState("idle"); // idle | submitting | success | redirecting
  const [waUrl, setWaUrl] = React.useState("");
  const [form, setForm] = React.useState({ name: "", phone: "", email: "", treatment: RM_TREATMENTS[0], message: "" });
  const isStack = useNarrow(920);
  const isPhone = useNarrow(640);

  // mount / unmount with transition
  React.useEffect(() => {
    let t;
    if (open) { setRender(true); t = setTimeout(() => setShown(true), 20); }
    else { setShown(false); t = setTimeout(() => { setRender(false); setStep("idle"); }, 340); }
    return () => clearTimeout(t);
  }, [open]);

  // body scroll lock + Esc
  React.useEffect(() => {
    if (!render) return;
    document.body.style.overflow = "hidden";
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => { document.body.style.overflow = ""; window.removeEventListener("keydown", onKey); };
  }, [render, onClose]);

  if (!render) return null;

  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  const submit = (e) => {
    e.preventDefault();
    // LP: vai direto pro WhatsApp com a mensagem pronta.
    if (lead) {
      const url = "https://wa.me/" + RM_WA_NUMBER + "?text=" +
        encodeURIComponent(lead.waMessage((form.name || "").trim()));
      setWaUrl(url);
      setStep("redirecting");
      // Conversão pro Meta Pixel antes de sair da página.
      if (window.fbq) window.fbq("track", "Lead", { content_name: lead.treatment });
      // Pequena folga pro pixel disparar; o link manual abaixo cobre bloqueio de redirect.
      setTimeout(() => { window.location.href = url; }, 350);
      return;
    }
    setStep("submitting");
    setTimeout(() => setStep("success"), 1400);
  };

  const waHref = () => {
    const msg = "Olá! Sou " + (form.name || "").trim() + " e gostaria de agendar uma avaliação"
      + (form.treatment ? " — " + form.treatment : "") + ".";
    return "https://wa.me/" + RM_WA_NUMBER + "?text=" + encodeURIComponent(msg);
  };

  const inputStyle = {
    width: "100%", padding: "13px 16px", borderRadius: "var(--radius-md)",
    background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.16)",
    // 16px é o mínimo que evita o zoom automático do iOS ao focar o campo.
    color: "#fff", fontSize: "16px", fontFamily: "var(--font-body)", outline: "none",
    transition: "border-color var(--dur-fast) var(--ease-out), box-shadow var(--dur-fast) var(--ease-out)",
  };
  const labelStyle = {
    display: "block", fontSize: "11px", letterSpacing: "0.14em", textTransform: "uppercase",
    color: "rgba(255,255,255,0.6)", marginBottom: "7px",
  };
  const onFocus = (e) => { e.target.style.borderColor = "var(--rm-gold-400)"; e.target.style.boxShadow = "0 0 0 3px rgba(197,160,89,0.18)"; };
  const onBlur = (e) => { e.target.style.borderColor = "rgba(255,255,255,0.16)"; e.target.style.boxShadow = "none"; };

  const Tick = () => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="var(--rm-gold-500)" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" style={{ flex: "none", marginTop: 2 }}><path d="M20 6 9 17l-5-5" /></svg>
  );

  return (
    <div
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
      style={{
        position: "fixed", inset: 0, zIndex: 200, display: "flex",
        alignItems: "center", justifyContent: "center", padding: isPhone ? 0 : "24px",
        background: "rgba(11,16,24,0.68)", backdropFilter: "blur(6px)",
        opacity: shown ? 1 : 0, transition: "opacity var(--dur-base) var(--ease-out)",
      }}
      role="dialog" aria-modal="true" aria-label="Agendar avaliação"
    >
      <div style={{
        position: "relative", width: "100%", maxWidth: "1040px",
        height: isPhone ? "100%" : "auto", maxHeight: isPhone ? "100%" : "92vh",
        // Na LP o formulário sobe pro topo quando empilha — é a ação da página.
        display: "flex", flexDirection: isStack ? (lead ? "column-reverse" : "column") : "row",
        background: "linear-gradient(155deg, var(--rm-navy-800) 0%, var(--rm-navy-900) 70%)",
        borderRadius: isPhone ? 0 : "var(--radius-xl)", overflow: "hidden",
        boxShadow: "var(--shadow-media)", color: "#fff",
        transform: shown ? "translateY(0) scale(1)" : "translateY(16px) scale(0.98)",
        opacity: shown ? 1 : 0,
        transition: "transform var(--dur-base) var(--ease-out), opacity var(--dur-base) var(--ease-out)",
        overflowY: isStack ? "auto" : "hidden",
      }}>
        {/* gold ambient glow */}
        <div style={{ position: "absolute", top: "-30%", right: "-10%", width: "60%", height: "80%", background: "radial-gradient(circle, rgba(197,160,89,0.16) 0%, rgba(197,160,89,0) 70%)", pointerEvents: "none" }} />

        {/* Close */}
        <button onClick={onClose} aria-label="Fechar"
          style={{ position: "absolute", top: 16, right: 16, zIndex: 5, width: 40, height: 40, borderRadius: "50%", border: "none", cursor: "pointer", background: "rgba(255,255,255,0.1)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", backdropFilter: "blur(6px)", transition: "background var(--dur-fast) var(--ease-out)" }}
          onMouseEnter={(e) => (e.currentTarget.style.background = "rgba(255,255,255,0.2)")}
          onMouseLeave={(e) => (e.currentTarget.style.background = "rgba(255,255,255,0.1)")}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"><path d="M18 6 6 18M6 6l12 12" /></svg>
        </button>

        {/* Left — brand / reassurance */}
        <div style={{ position: "relative", flex: "1 1 0", padding: isPhone ? "40px 24px 8px" : "52px 48px", display: "flex", flexDirection: "column", gap: "28px", justifyContent: "center" }}>
          <div style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
            <span className="rm-eyebrow" style={{ color: "var(--text-gold-on-dark)" }}>Agende agora</span>
            <h2 style={{ fontFamily: "var(--font-display)", fontSize: "clamp(1.9rem, 3.4vw, 2.75rem)", lineHeight: 1.05, color: "#fff", margin: 0, whiteSpace: "pre-line" }}>
              {lead ? lead.title : "Vamos cuidar\ndo seu sorriso"}
            </h2>
            <p style={{ fontSize: "16px", lineHeight: 1.6, color: "rgba(255,255,255,0.72)", margin: 0, maxWidth: "40ch" }}>
              Uma avaliação individual para entender seus objetivos e desenhar o plano ideal. Preencha e nossa equipe entra em contato.
            </p>
          </div>
          <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: "12px" }}>
            {["Minimamente invasivo, expressão preservada", "Planejamento individual e resultado natural", "+18 anos de experiência clínica"].map((t) => (
              <li key={t} style={{ display: "flex", gap: "12px", alignItems: "flex-start", fontSize: "15px", color: "rgba(255,255,255,0.9)" }}><Tick />{t}</li>
            ))}
          </ul>
          {!isStack && (
            <figure style={{ margin: 0, paddingTop: "24px", borderTop: "1px solid rgba(255,255,255,0.14)" }}>
              <blockquote style={{ margin: 0, fontSize: "16px", lineHeight: 1.6, color: "rgba(255,255,255,0.86)", fontStyle: "italic" }}>
                “Recuperei o frescor do olhar sem perder a minha expressão.”
              </blockquote>
              <figcaption style={{ marginTop: "10px", fontSize: "13px", color: "var(--text-gold-on-dark)" }}>Marina A. · Rejuvenescimento do olhar</figcaption>
            </figure>
          )}
        </div>

        {/* Right — form / success */}
        <div style={{ position: "relative", flex: "1 1 0", padding: isPhone ? "16px 24px 40px" : "52px 48px", display: "flex", alignItems: "center", justifyContent: "center" }}>
          <div style={{ width: "100%", maxWidth: "420px", background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.14)", borderRadius: "var(--radius-lg)", padding: isPhone ? "24px 20px" : "28px" }}>
            {step === "success" ? (
              <div style={{ display: "flex", flexDirection: "column", alignItems: "center", textAlign: "center", gap: "22px", padding: "16px 0" }}>
                <span style={{ width: 72, height: 72, borderRadius: "50%", background: "var(--rm-gold-500)", display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 12px 30px -8px rgba(197,160,89,0.6)" }}>
                  <svg width="34" height="34" viewBox="0 0 24 24" fill="none" stroke="var(--rm-navy-900)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5" /></svg>
                </span>
                <div>
                  <h3 style={{ fontFamily: "var(--font-display)", fontSize: "26px", color: "#fff", margin: "0 0 8px" }}>Recebemos seu contato!</h3>
                  <p style={{ fontSize: "15px", lineHeight: 1.6, color: "rgba(255,255,255,0.72)", margin: 0 }}>
                    Nossa equipe vai falar com você em breve para agendar sua avaliação. Quer adiantar? Fale agora no WhatsApp.
                  </p>
                </div>
                <a href={waHref()} target="_blank" rel="noopener"
                  style={{ display: "inline-flex", alignItems: "center", gap: "10px", padding: "13px 24px", borderRadius: "var(--radius-md)", background: "#25D366", color: "#0b1018", fontWeight: 600, fontSize: "15px", textDecoration: "none" }}>
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M12.04 2c-5.46 0-9.9 4.44-9.9 9.9 0 1.75.46 3.45 1.32 4.95L2 22l5.3-1.39c1.45.79 3.08 1.21 4.74 1.21 5.46 0 9.9-4.44 9.9-9.9S17.5 2 12.04 2Zm5.8 14.03c-.24.68-1.42 1.32-1.95 1.36-.5.05-.5.4-3.16-.66-2.67-1.05-4.35-3.76-4.48-3.94-.13-.18-1.07-1.42-1.07-2.71 0-1.29.68-1.92.92-2.19.24-.26.53-.33.7-.33.18 0 .35 0 .5.01.16.01.38-.06.59.45.24.58.82 2 .89 2.14.07.15.12.32.02.5-.09.18-.14.29-.27.45-.13.15-.28.34-.4.46-.13.13-.27.28-.12.54.15.26.66 1.09 1.42 1.76.98.87 1.8 1.14 2.06 1.27.26.13.41.11.56-.07.15-.18.65-.76.82-1.02.17-.26.35-.22.59-.13.24.09 1.52.72 1.78.85.26.13.43.19.5.3.06.11.06.64-.18 1.32Z" /></svg>
                  Falar no WhatsApp
                </a>
                <button onClick={onClose} style={{ background: "none", border: "none", color: "rgba(255,255,255,0.55)", cursor: "pointer", fontSize: "14px", textDecoration: "underline", padding: 6 }}>Voltar ao site</button>
              </div>
            ) : step === "redirecting" ? (
              <div style={{ display: "flex", flexDirection: "column", alignItems: "center", textAlign: "center", gap: "20px", padding: "16px 0" }}>
                <span style={{ width: 56, height: 56, borderRadius: "50%", background: "#25D366", display: "flex", alignItems: "center", justifyContent: "center" }}>
                  <svg width="28" height="28" viewBox="0 0 24 24" fill="#0b1018"><path d="M12.04 2c-5.46 0-9.9 4.44-9.9 9.9 0 1.75.46 3.45 1.32 4.95L2 22l5.3-1.39c1.45.79 3.08 1.21 4.74 1.21 5.46 0 9.9-4.44 9.9-9.9S17.5 2 12.04 2Zm5.8 14.03c-.24.68-1.42 1.32-1.95 1.36-.5.05-.5.4-3.16-.66-2.67-1.05-4.35-3.76-4.48-3.94-.13-.18-1.07-1.42-1.07-2.71 0-1.29.68-1.92.92-2.19.24-.26.53-.33.7-.33.18 0 .35 0 .5.01.16.01.38-.06.59.45.24.58.82 2 .89 2.14.07.15.12.32.02.5-.09.18-.14.29-.27.45-.13.15-.28.34-.4.46-.13.13-.27.28-.12.54.15.26.66 1.09 1.42 1.76.98.87 1.8 1.14 2.06 1.27.26.13.41.11.56-.07.15-.18.65-.76.82-1.02.17-.26.35-.22.59-.13.24.09 1.52.72 1.78.85.26.13.43.19.5.3.06.11.06.64-.18 1.32Z" /></svg>
                </span>
                <div>
                  <h3 style={{ fontFamily: "var(--font-display)", fontSize: "24px", color: "#fff", margin: "0 0 8px" }} role="status">Abrindo o WhatsApp…</h3>
                  <p style={{ fontSize: "15px", lineHeight: 1.6, color: "rgba(255,255,255,0.72)", margin: 0 }}>
                    Sua mensagem já vai pronta. Se não abrir sozinho, toque no botão abaixo.
                  </p>
                </div>
                <a href={waUrl}
                  style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: "100%", padding: "14px 24px", borderRadius: "var(--radius-md)", background: "#25D366", color: "#0b1018", fontWeight: 600, fontSize: "16px", textDecoration: "none" }}>
                  Abrir o WhatsApp
                </a>
              </div>
            ) : (
              <form onSubmit={submit} style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
                <div style={{ marginBottom: "2px" }}>
                  <h3 style={{ fontFamily: "var(--font-display)", fontSize: "22px", color: "#fff", margin: "0 0 4px" }}>Solicitar avaliação</h3>
                  <p style={{ fontSize: "13px", color: "rgba(255,255,255,0.6)", margin: 0 }}>
                    {lead ? "Dois campos e você fala com a gente no WhatsApp." : "Preencha e entramos em contato."}
                  </p>
                </div>
                <div>
                  <label htmlFor="rm-name" style={labelStyle}>Nome completo</label>
                  <input id="rm-name" required type="text" placeholder="Seu nome" autoComplete="name" autoCapitalize="words"
                    value={form.name} onChange={set("name")} onFocus={onFocus} onBlur={onBlur} style={inputStyle} />
                </div>
                <div style={{ display: "grid", gridTemplateColumns: isPhone || lead ? "1fr" : "1fr 1fr", gap: "14px" }}>
                  <div>
                    <label htmlFor="rm-phone" style={labelStyle}>WhatsApp</label>
                    <input id="rm-phone" required type="tel" inputMode="tel" placeholder="(43) 90000-0000" autoComplete="tel"
                      value={form.phone} onChange={set("phone")} onFocus={onFocus} onBlur={onBlur} style={inputStyle} />
                  </div>
                  {!lead && (
                    <div>
                      <label htmlFor="rm-email" style={labelStyle}>E-mail</label>
                      <input id="rm-email" type="email" inputMode="email" placeholder="voce@email.com" autoComplete="email"
                        value={form.email} onChange={set("email")} onFocus={onFocus} onBlur={onBlur} style={inputStyle} />
                    </div>
                  )}
                </div>
                {!lead && (
                  <div>
                    <label htmlFor="rm-treatment" style={labelStyle}>Tratamento de interesse</label>
                    <select id="rm-treatment" value={form.treatment} onChange={set("treatment")} onFocus={onFocus} onBlur={onBlur} style={{ ...inputStyle, appearance: "none", cursor: "pointer" }}>
                      {RM_TREATMENTS.map((t) => <option key={t} value={t} style={{ background: "#1b2432", color: "#fff" }}>{t}</option>)}
                    </select>
                  </div>
                )}
                {!lead && (
                  <div>
                    <label htmlFor="rm-msg" style={labelStyle}>Mensagem <span style={{ textTransform: "none", letterSpacing: 0, opacity: 0.6 }}>(opcional)</span></label>
                    <textarea id="rm-msg" rows={2} placeholder="Conte um pouco sobre o que procura…" value={form.message} onChange={set("message")} onFocus={onFocus} onBlur={onBlur} style={{ ...inputStyle, resize: "none" }} />
                  </div>
                )}
                <button type="submit" disabled={step === "submitting"}
                  style={{ marginTop: "4px", width: "100%", padding: "14px", borderRadius: "var(--radius-md)", border: "none", cursor: step === "submitting" ? "default" : "pointer", background: "var(--rm-gold-500)", color: "var(--rm-navy-900)", fontFamily: "var(--font-body)", fontWeight: 600, fontSize: "15px", letterSpacing: "0.02em", display: "flex", alignItems: "center", justifyContent: "center", gap: "10px", opacity: step === "submitting" ? 0.75 : 1, transition: "opacity var(--dur-fast) var(--ease-out)" }}>
                  {step === "submitting" ? (
                    <>
                      <span style={{ width: 16, height: 16, border: "2px solid var(--rm-navy-900)", borderTopColor: "transparent", borderRadius: "50%", display: "inline-block", animation: "rm-spin 0.7s linear infinite" }} />
                      Enviando…
                    </>
                  ) : lead ? "Solicitar contato no WhatsApp" : "Solicitar contato"}
                </button>
                <p style={{ fontSize: "11px", textAlign: "center", color: "rgba(255,255,255,0.45)", margin: 0 }}>
                  {lead
                    ? "Ao enviar, abrimos o WhatsApp com sua mensagem pronta. Seus dados são usados apenas para o contato da clínica."
                    : "Seus dados são usados apenas para o contato da clínica."}
                </p>
              </form>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

function Hero({ leadPreset } = {}) {
  const { Button, WhatsAppButton, Badge } = window.DrRenanMouraDesignSystem_c23fa8;
  const [booking, setBooking] = React.useState(false);
  return (
    <section style={{ position: "relative", minHeight: "100vh", display: "flex", alignItems: "flex-end", overflow: "hidden", background: "var(--rm-navy-900)" }}>
      <img src="assets/images/doctor-portrait-tablet.png" alt="Dr. Renan Moura"
        style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", objectPosition: "center 20%" }} />
      <div style={{ position: "absolute", inset: 0, background: "linear-gradient(90deg, rgba(20,27,38,0.82) 0%, rgba(20,27,38,0.45) 45%, rgba(20,27,38,0.15) 100%)" }} />
      <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg, rgba(20,27,38,0.35) 0%, rgba(20,27,38,0) 30%, rgba(20,27,38,0.65) 100%)" }} />

      <div className="rm-x40" style={{ position: "relative", width: "100%", maxWidth: "var(--content-max)", margin: "0 auto", padding: "0 40px 120px", color: "#fff" }}>
        <div style={{ maxWidth: "760px", display: "flex", flexDirection: "column", gap: "28px" }} data-reveal>
          <Badge variant="onDark">Odontologia premium &middot; Rejuvenescimento facial</Badge>
          <h1 style={{ fontFamily: "var(--font-display)", fontSize: "var(--text-display-xl)", lineHeight: 1.02, letterSpacing: "-0.01em", color: "#fff", margin: 0 }}>
            Beleza natural<br />com olhar rejuvenescido.
          </h1>
          <p style={{ fontSize: "20px", lineHeight: 1.6, color: "rgba(255,255,255,0.82)", maxWidth: "52ch", margin: 0 }}>
            Odontologia avançada e rejuvenescimento facial minimamente invasivo — para restaurar a harmonia do rosto, preservando a sua expressão.
          </p>
          <div style={{ display: "flex", gap: "16px", flexWrap: "wrap", marginTop: "8px" }}>
            <button onClick={() => setBooking(true)}
              style={{ display: "inline-flex", alignItems: "center", gap: "10px", height: "56px", padding: "0 28px", borderRadius: "var(--radius-pill)", border: "none", cursor: "pointer", background: "var(--rm-gold-500)", color: "var(--rm-navy-900)", fontFamily: "var(--font-body)", fontSize: "17px", fontWeight: 600, letterSpacing: "0.02em", boxShadow: "0 14px 34px -14px rgba(197,160,89,0.7)", transition: "transform var(--dur-fast) var(--ease-out), box-shadow var(--dur-fast) var(--ease-out)" }}
              onMouseEnter={(e) => { e.currentTarget.style.transform = "translateY(-2px)"; e.currentTarget.style.boxShadow = "0 20px 44px -14px rgba(197,160,89,0.8)"; }}
              onMouseLeave={(e) => { e.currentTarget.style.transform = "none"; e.currentTarget.style.boxShadow = "0 14px 34px -14px rgba(197,160,89,0.7)"; }}>
              Agendar avaliação
              <svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 6l6 6-6 6" /></svg>
            </button>
            <Button variant="outline" size="lg" href="#rejuvenescimento" style={{ color: "#fff", borderColor: "rgba(255,255,255,0.4)" }}>Conhecer a técnica</Button>
          </div>
        </div>
      </div>

      <BookingModal open={booking} onClose={() => setBooking(false)} preset={leadPreset} />
    </section>
  );
}
window.Hero = Hero;
