// ====================== NOSSOS DIFERENCIAIS (dark) ======================
const DIFERENCIAIS = [
  { icon: IconStar, t: "Grandes marcas", s: "3M, BIC, Ypê, Tilibra, Copobras e outros líderes de mercado para garantir qualidade." },
  { icon: IconBolt, t: "Entrega ágil", s: "Atendemos Recife e região com rapidez. Seu pedido entregue no prazo certo." },
  { icon: IconUsers, t: "Atendimento personalizado", s: "Nossa equipe conhece as necessidades de cada cliente e oferece soluções sob medida." },
  { icon: IconDollar, t: "Melhor custo-benefício", s: "Preço justo, condições flexíveis e volume garantindo a melhor relação qualidade-preço." },
];

function Diferenciais() {
  return (
    <section className="jgf-dif-sec" style={{ display: "flex", justifyContent: "center", background: "var(--navy)", padding: "76px 0 84px", position: "relative", overflow: "hidden" }}>
      <div aria-hidden="true" style={{ position: "absolute", top: -60, left: "50%", transform: "translateX(-50%)", width: 720, height: 360, background: "radial-gradient(ellipse, rgba(245,168,0,.10), transparent 70%)" }} />
      <div style={{ width: "100%", maxWidth: 1320, padding: "0 26px", position: "relative", zIndex: 2 }}>
        <div className="jgf-dif-head" style={{ textAlign: "center", marginBottom: 50 }}>
          <div className="jgf-dif-eyebrow" style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 14, marginBottom: 16 }}>
            <span style={{ width: 30, height: 2, background: "var(--yellow)", opacity: .85 }} />
            <span style={{ color: "var(--yellow)", fontWeight: 700, fontSize: 12, letterSpacing: ".24em" }}>POR QUE ESCOLHER A JGF</span>
            <span style={{ width: 30, height: 2, background: "var(--yellow)", opacity: .85 }} />
          </div>
          <h2 className="jgf-dif-title" style={{ margin: 0, color: "#fff", fontWeight: 800, fontSize: 40, letterSpacing: "-.02em" }}>Nossos diferenciais</h2>
          <p className="jgf-dif-sub" style={{ color: "#aeb9d0", fontSize: 16, fontWeight: 500, margin: "16px auto 0", maxWidth: 540, lineHeight: 1.55, textWrap: "pretty" }}>
            Mais do que um fornecedor, somos um parceiro estratégico para o crescimento da sua empresa.
          </p>
        </div>
        <div className="jgf-grid-4 jgf-dif-grid" style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 22 }}>
          {DIFERENCIAIS.map((d, i) => (
            <div key={i} className="difC-card" style={{ position: "relative", background: "linear-gradient(165deg, rgba(255,255,255,.07), rgba(255,255,255,.025))", border: "1px solid rgba(255,255,255,.1)", borderRadius: 18, padding: "34px 26px 30px", textAlign: "center", transition: "transform .22s ease, border-color .22s ease, box-shadow .22s ease" }}>
              <div style={{ position: "relative", width: 66, height: 66, margin: "0 auto 22px" }}>
                <span className="difC-glow" aria-hidden="true" style={{ position: "absolute", inset: -6, borderRadius: "50%", background: "radial-gradient(circle, rgba(245,168,0,.45), transparent 70%)", opacity: .5, transition: "opacity .25s" }} />
                <div style={{ position: "relative", width: 66, height: 66, borderRadius: "50%", background: "rgba(245,168,0,.12)", border: "1.5px solid rgba(245,168,0,.4)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--yellow)" }}>
                  <d.icon size={28} stroke={1.8} />
                </div>
              </div>
              <div style={{ color: "#fff", fontWeight: 700, fontSize: 17.5, marginBottom: 11 }}>{d.t}</div>
              <p style={{ color: "#9aa6c0", fontSize: 13, lineHeight: 1.62, margin: 0, fontWeight: 400, textWrap: "pretty" }}>{d.s}</p>
            </div>
          ))}
        </div>
      </div>
      <style>{`.difC-card:hover{transform:translateY(-6px);border-color:rgba(245,168,0,.4);box-shadow:0 20px 44px rgba(0,0,0,.28);}.difC-card:hover .difC-glow{opacity:1;}`}</style>
    </section>
  );
}

// ====================== FALE CONOSCO + ORÇAMENTO ======================
const CONTACTS = [
  { icon: IconPhone, color: "#1a73e8", bg: "#eaf1fd", v: "(81) 3127-0069", l: "Telefone principal", href: "tel:+558131270069" },
  { icon: IconPhone, color: "#1a73e8", bg: "#eaf1fd", v: "(81) 3127-0070", l: "Linha adicional", href: "tel:+558131270070" },
  { icon: IconMail, color: "#e09a00", bg: "#fdf3e0", v: "compras1@jgfdistribuidora.com.br", l: "E-mail de compras", href: "mailto:compras1@jgfdistribuidora.com.br" },
  { icon: IconInstagram, color: "#2e9b57", bg: "#e7f5ed", v: "@jgf_distribuidora", l: "Instagram", href: "https://instagram.com/jgf_distribuidora" },
];
const WA_NUMBER = "558173008306"; // ← número de destino do WhatsApp

function fmtCNPJc(v) {
  const d = (v || "").replace(/\D/g, "").slice(0, 14);
  let o = d;
  if (d.length > 2) o = d.slice(0, 2) + "." + d.slice(2);
  if (d.length > 5) o = d.slice(0, 2) + "." + d.slice(2, 5) + "." + d.slice(5);
  if (d.length > 8) o = d.slice(0, 2) + "." + d.slice(2, 5) + "." + d.slice(5, 8) + "/" + d.slice(8);
  if (d.length > 12) o = d.slice(0, 2) + "." + d.slice(2, 5) + "." + d.slice(5, 8) + "/" + d.slice(8, 12) + "-" + d.slice(12);
  return o;
}
function fmtPhonec(v) {
  const d = (v || "").replace(/\D/g, "").slice(0, 11);
  if (d.length <= 2) return d.length ? "(" + d : "";
  if (d.length <= 6) return "(" + d.slice(0, 2) + ") " + d.slice(2);
  if (d.length <= 10) return "(" + d.slice(0, 2) + ") " + d.slice(2, 6) + "-" + d.slice(6);
  return "(" + d.slice(0, 2) + ") " + d.slice(2, 7) + "-" + d.slice(7);
}

function ContactSection({ onToast }) {
  const [form, setForm] = React.useState({ cnpj: "", razao: "", email: "", tel: "", cat: "", msg: "" });
  const [lookup, setLookup] = React.useState(""); // "" | loading | ok | fail
  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  const buscarCNPJ = async (raw) => {
    const digits = (raw || "").replace(/\D/g, "");
    if (digits.length !== 14) return;
    setLookup("loading");
    try {
      const r = await fetch("https://brasilapi.com.br/api/cnpj/v1/" + digits);
      if (!r.ok) throw new Error("nf");
      const d = await r.json();
      setForm((f) => {
        const tel = d.ddd_telefone_1 || d.ddd_telefone_2 || "";
        return {
          ...f,
          razao: d.razao_social || d.nome_fantasia || f.razao,
          tel: (tel && tel.replace(/\D/g, "").length >= 10) ? fmtPhonec(tel) : f.tel,
          email: d.email ? (d.email || "").toLowerCase() : f.email,
        };
      });
      setLookup("ok");
    } catch (_) { setLookup("fail"); }
  };

  const submit = (e) => {
    e.preventDefault();
    if (form.cnpj.replace(/\D/g, "").length !== 14) { onToast && onToast("Informe um CNPJ válido com 14 dígitos"); return; }
    if (!form.razao.trim() || !form.tel.trim()) { onToast && onToast("Preencha ao menos razão social e telefone"); return; }
    const txt = `*Solicitação de orçamento JGF*%0A%0A*CNPJ:* ${form.cnpj}%0A*Razão social:* ${form.razao}%0A*E-mail:* ${form.email || "-"}%0A*Telefone:* ${form.tel}%0A*Categoria:* ${form.cat || "-"}%0A*Mensagem:* ${form.msg || "-"}`;
    window.open(`https://wa.me/${WA_NUMBER}?text=${txt}`, "_blank");
    onToast && onToast("Abrindo WhatsApp com seu orçamento…");
  };

  const inputBase = {
    width: "100%", background: "rgba(255,255,255,.05)", border: "1.5px solid rgba(255,255,255,.13)",
    borderRadius: 9, padding: "13px 15px", fontSize: 14, color: "#fff", outline: "none",
    fontFamily: "var(--ff)", fontWeight: 500, transition: "border-color .15s, background .15s",
  };
  const onFoc = (e) => { e.target.style.borderColor = "var(--yellow)"; e.target.style.background = "rgba(255,255,255,.08)"; };
  const onBlur = (e) => { e.target.style.borderColor = "rgba(255,255,255,.13)"; e.target.style.background = "rgba(255,255,255,.05)"; };
  const Label = ({ children }) => <label style={{ display: "block", fontSize: 11.5, fontWeight: 700, color: "#8a97b5", letterSpacing: ".08em", marginBottom: 8 }}>{children}</label>;

  return (
    <section style={{ display: "flex", justifyContent: "center", padding: "64px 0 70px" }}>
      <div className="jgf-contact" style={{ width: "100%", maxWidth: 1320, padding: "0 26px", display: "grid", gridTemplateColumns: "1fr 1.05fr", gap: 56, alignItems: "start" }}>
        {/* LEFT — channels */}
        <div>
          <div className="jgf-contact-eyebrow" style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 14 }}>
            <span style={{ color: "var(--navy)", fontWeight: 700, fontSize: 12.5, letterSpacing: ".22em" }}>FALE CONOSCO</span>
            <span style={{ width: 34, height: 2, background: "var(--navy)" }} />
          </div>
          <h2 className="jgf-contact-title" style={{ margin: 0, color: "var(--navy)", fontWeight: 800, fontSize: 40, lineHeight: 1.05, letterSpacing: "-.015em" }}>Pronto para fazer<br />seu pedido?</h2>
          <p className="jgf-contact-sub" style={{ color: "#6b7280", fontSize: 16, fontWeight: 500, margin: "20px 0 32px", lineHeight: 1.55, maxWidth: 380, textWrap: "pretty" }}>
            Entre em contato pelos nossos canais ou preencha o formulário e retornamos rapidamente.
          </p>
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {CONTACTS.map((c, i) => (
              <a key={i} href={c.href} target={c.href.startsWith("http") ? "_blank" : undefined} rel={c.href.startsWith("http") ? "noopener noreferrer" : undefined}
                style={{ display: "flex", alignItems: "center", gap: 16, background: "#fff", border: "1px solid var(--line)", borderRadius: 12, padding: "16px 18px", boxShadow: "0 1px 3px rgba(16,30,60,.05)", textDecoration: "none", cursor: "pointer", transition: "transform .15s, box-shadow .15s, border-color .15s" }}
                onMouseEnter={(e) => { e.currentTarget.style.transform = "translateX(4px)"; e.currentTarget.style.boxShadow = "var(--shadow-soft)"; e.currentTarget.style.borderColor = c.color; }}
                onMouseLeave={(e) => { e.currentTarget.style.transform = "none"; e.currentTarget.style.boxShadow = "0 1px 3px rgba(16,30,60,.05)"; e.currentTarget.style.borderColor = "var(--line)"; }}>
                <div style={{ width: 44, height: 44, borderRadius: 10, background: c.bg, color: c.color, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                  <c.icon size={21} stroke={1.8} />
                </div>
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div style={{ fontWeight: 700, fontSize: 15, color: "var(--navy)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.v}</div>
                  <div style={{ fontSize: 12.5, color: "#8a93a6", fontWeight: 500, marginTop: 2 }}>{c.l}</div>
                </div>
                <span style={{ color: "#c3cadb", flexShrink: 0, display: "flex" }}><IconArrowR size={18} stroke={2} /></span>
              </a>
            ))}
          </div>
        </div>

        {/* RIGHT — quote form */}
        <div style={{ position: "relative", background: "var(--navy)", borderRadius: 18, padding: "38px 38px 40px", boxShadow: "0 24px 60px rgba(16,30,60,.28)", overflow: "hidden" }}>
          <div aria-hidden="true" style={{ position: "absolute", top: 0, left: 0, right: 0, height: 4, background: "linear-gradient(90deg, var(--navy-2), var(--yellow))" }} />
          <h3 style={{ margin: "0 0 6px", color: "#fff", fontWeight: 800, fontSize: 24 }}>Solicitar orçamento</h3>
          <p style={{ margin: "0 0 26px", color: "#9aa6c0", fontSize: 13.5, lineHeight: 1.5, maxWidth: 420 }}>
            Preencha os dados abaixo e nossa equipe entra em contato com a melhor proposta.
          </p>
          <form onSubmit={submit} style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <div><Label>CNPJ</Label>
              <div style={{ position: "relative" }}>
                <input value={form.cnpj}
                  onChange={(e) => { const v = fmtCNPJc(e.target.value); setForm((f) => ({ ...f, cnpj: v })); if (v.replace(/\D/g, "").length === 14) buscarCNPJ(v); }}
                  onBlur={(e) => { buscarCNPJ(e.target.value); onBlur(e); }} onFocus={onFoc}
                  inputMode="numeric" placeholder="00.000.000/0000-00" style={{ ...inputBase, paddingRight: 96 }} />
                {lookup === "loading" && <span style={{ position: "absolute", right: 14, top: "50%", transform: "translateY(-50%)", fontSize: 11.5, fontWeight: 700, color: "#9aa6c0" }}>buscando…</span>}
                {lookup === "ok" && <span style={{ position: "absolute", right: 14, top: "50%", transform: "translateY(-50%)", color: "var(--yellow)", display: "flex" }}><IconCheck size={18} stroke={2.2} /></span>}
              </div>
              {lookup === "fail" && <div style={{ fontSize: 11.5, color: "#f0a0a0", fontWeight: 600, marginTop: 6 }}>CNPJ não encontrado automaticamente. Preencha manualmente.</div>}
            </div>
            <div><Label>RAZÃO SOCIAL</Label>
              <input value={form.razao} onChange={set("razao")} onFocus={onFoc} onBlur={onBlur} placeholder="Nome da empresa" style={inputBase} /></div>
            <div><Label>E-MAIL</Label>
              <input value={form.email} onChange={set("email")} type="email" onFocus={onFoc} onBlur={onBlur} placeholder="contato@empresa.com.br" style={inputBase} /></div>
            <div><Label>TELEFONE</Label>
              <input value={form.tel} onChange={(e) => setForm((f) => ({ ...f, tel: fmtPhonec(e.target.value) }))} inputMode="numeric" onFocus={onFoc} onBlur={onBlur} placeholder="(81) 9 0000-0000" style={inputBase} /></div>
            <div><Label>CATEGORIA DE INTERESSE</Label>
              <select value={form.cat} onChange={set("cat")} onFocus={onFoc} onBlur={onBlur}
                style={{ ...inputBase, appearance: "none", WebkitAppearance: "none", color: form.cat ? "#fff" : "#7886a3",
                  backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='none' stroke='%237886a3' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><path d='m4 6 4 4 4-4'/></svg>\")",
                  backgroundRepeat: "no-repeat", backgroundPosition: "right 14px center", paddingRight: 40, cursor: "pointer" }}>
                <option value="" style={{ color: "#333" }}>Selecione uma categoria</option>
                {CATEGORIES.map((c) => <option key={c.id} value={c.label} style={{ color: "#333" }}>{c.label}</option>)}
                <option value="Outros" style={{ color: "#333" }}>Outros</option>
              </select></div>
            <div><Label>MENSAGEM</Label>
              <textarea value={form.msg} onChange={set("msg")} onFocus={onFoc} onBlur={onBlur} placeholder="Descreva o que sua empresa precisa…" rows={4}
                style={{ ...inputBase, resize: "vertical", minHeight: 96, lineHeight: 1.5 }} /></div>
            <button type="submit" className="jgf-wa-submit" style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 11, width: "100%", background: "var(--yellow)", color: "var(--navy)", fontWeight: 800, fontSize: 15.5, padding: "16px", borderRadius: 10, marginTop: 4, whiteSpace: "nowrap", boxShadow: "0 8px 22px rgba(245,168,0,.3)", transition: "transform .15s, box-shadow .15s" }}
              onMouseEnter={(e) => { e.currentTarget.style.transform = "translateY(-2px)"; e.currentTarget.style.boxShadow = "0 12px 28px rgba(245,168,0,.42)"; }}
              onMouseLeave={(e) => { e.currentTarget.style.transform = "none"; e.currentTarget.style.boxShadow = "0 8px 22px rgba(245,168,0,.3)"; }}>
              <IconWhatsApp size={21} />Enviar pelo WhatsApp
            </button>
          </form>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Diferenciais, ContactSection });
