// Demo request modal — opens from any .btn linking to #demo; sends via e-mail
const { useState: useStateDF, useEffect: useEffectDF, useRef: useRefDF } = React;

const DEMO_EMAIL = "comercial@naescala.com.br";

const DEMO_FIELDS = [
  { name: "razao", label: "Razão social", req: true, span: 2, ac: "organization" },
  { name: "responsavel", label: "Nome do responsável", req: true, span: 2, ac: "name" },
  { name: "cnpj", label: "CNPJ", req: true, span: 1, ph: "00.000.000/0000-00" },
  { name: "cep", label: "CEP", req: false, span: 1, ph: "00000-000", ac: "postal-code" },
  { name: "rua", label: "Rua", req: false, span: 2, ac: "address-line1" },
  { name: "numero", label: "Número", req: false, span: 1 },
  { name: "bairro", label: "Bairro", req: false, span: 1 },
  { name: "cidade", label: "Cidade", req: false, span: 1 },
  { name: "estado", label: "Estado", req: false, span: 1 },
  { name: "telefone", label: "Telefone", req: true, span: 1, type: "tel", ph: "(00) 00000-0000", ac: "tel" },
  { name: "email", label: "E-mail", req: true, span: 1, type: "email", ph: "voce@empresa.com.br", ac: "email" },
];

function DemoModal() {
  const [open, setOpen] = useStateDF(false);
  const [vals, setVals] = useStateDF({});
  const [errors, setErrors] = useStateDF({});
  const [sent, setSent] = useStateDF(false);
  const firstRef = useRefDF(null);

  // open from any CTA button pointing to #demo
  useEffectDF(() => {
    const onClick = (e) => {
      const a = e.target.closest && e.target.closest("a.btn");
      if (a && (a.getAttribute("href") || "").indexOf("#demo") !== -1) {
        e.preventDefault();
        setOpen(true);
      }
    };
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    document.addEventListener("click", onClick);
    document.addEventListener("keydown", onKey);
    return () => { document.removeEventListener("click", onClick); document.removeEventListener("keydown", onKey); };
  }, []);

  useEffectDF(() => {
    document.body.style.overflow = open ? "hidden" : "";
    if (open) { setSent(false); setTimeout(() => firstRef.current && firstRef.current.focus(), 60); }
  }, [open]);

  const set = (name, v) => {
    setVals((p) => ({ ...p, [name]: v }));
    setErrors((p) => (p[name] ? { ...p, [name]: false } : p));
  };

  const validate = () => {
    const er = {};
    DEMO_FIELDS.forEach((f) => {
      const v = (vals[f.name] || "").trim();
      if (f.req && !v) er[f.name] = true;
      if (f.name === "email" && v && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) er[f.name] = true;
    });
    return er;
  };

  const buildBody = () => {
    const lines = ["Solicitação de demonstração — Na Escala", ""];
    DEMO_FIELDS.forEach((f) => {
      const v = (vals[f.name] || "").trim();
      if (v || f.req) lines.push(f.label + ": " + (v || "-"));
    });
    lines.push("", "Enviado pelo site naescala.com.br");
    return lines.join("\r\n");
  };

  const submit = (e) => {
    e.preventDefault();
    const er = validate();
    setErrors(er);
    if (Object.keys(er).length) {
      const first = DEMO_FIELDS.find((f) => er[f.name]);
      const el = document.getElementById("df-" + first.name);
      if (el) el.focus();
      return;
    }
    const subject = "Solicitação de demonstração — " + (vals.razao || "").trim();
    const mailto = "mailto:" + DEMO_EMAIL + "?subject=" + encodeURIComponent(subject) + "&body=" + encodeURIComponent(buildBody());
    window.location.href = mailto;
    setSent(true);
  };

  const copy = () => {
    const txt = "Para: " + DEMO_EMAIL + "\r\n" + buildBody();
    if (navigator.clipboard) navigator.clipboard.writeText(txt);
  };

  if (!open) return null;

  return (
    <div className="modal-ov" onMouseDown={(e) => { if (e.target === e.currentTarget) setOpen(false); }}>
      <div className="modal" role="dialog" aria-modal="true" aria-label="Solicitar demonstração">
        <button className="modal__close" onClick={() => setOpen(false)} aria-label="Fechar">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" /></svg>
        </button>

        {sent ? (
          <div className="modal__success">
            <span className="modal__check"><svg width="30" height="30" viewBox="0 0 24 24" fill="none"><path d="M4 12.5l5 5 11-12" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" /></svg></span>
            <h3>Quase lá!</h3>
            <p>Abrimos seu aplicativo de e-mail com a solicitação já preenchida. É só revisar e enviar para <b>{DEMO_EMAIL}</b>.</p>
            <p className="modal__notesm">Não abriu? Copie os dados e envie manualmente.</p>
            <div className="modal__actions">
              <button className="btn btn--outline btn--md" onClick={copy}><span>Copiar dados</span></button>
              <button className="btn btn--primary btn--md" onClick={() => setOpen(false)} icon={false}><span>Fechar</span></button>
            </div>
          </div>
        ) : (
          <React.Fragment>
            <div className="modal__head">
              <span className="eyebrow"><span className="eyebrow__dot" />Demonstração gratuita</span>
              <h3 className="modal__title">Agende sua demonstração</h3>
              <p className="modal__sub">Preencha os dados abaixo. Nossa equipe entra em contato para liberar seu teste de 30 dias.</p>
            </div>
            <form className="demoform" onSubmit={submit} noValidate>
              {DEMO_FIELDS.map((f, i) => (
                <div key={f.name} className={"field field--span" + f.span + (errors[f.name] ? " is-error" : "")}>
                  <label htmlFor={"df-" + f.name}>{f.label}{f.req && <span className="field__req">*</span>}</label>
                  <input
                    id={"df-" + f.name}
                    ref={i === 0 ? firstRef : null}
                    type={f.type || "text"}
                    placeholder={f.ph || ""}
                    autoComplete={f.ac || "off"}
                    value={vals[f.name] || ""}
                    onChange={(e) => set(f.name, e.target.value)}
                  />
                  {errors[f.name] && <span className="field__err">{f.name === "email" && (vals.email || "").trim() ? "E-mail inválido" : "Campo obrigatório"}</span>}
                </div>
              ))}
              <div className="demoform__foot">
                <p className="modal__note"><span className="field__req">*</span> Campos obrigatórios</p>
                <button type="submit" className="btn btn--primary btn--lg demoform__submit">
                  <span>Enviar solicitação</span>
                  <svg className="btn__arrow" width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M5 12h14M13 6l6 6-6 6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" /></svg>
                </button>
              </div>
            </form>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { DemoModal });
