/* global React, Icon */
const { useState: useW, useEffect: useWE, useRef: useWR } = React;

async function postContact(payload) {
  try {
    // await fetch("/api/contact/request", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) });
    await new Promise((r) => setTimeout(r, 700));
    return { ok: true };
  } catch { return { ok: false }; }
}

function ChatWidget({ waNumber }) {
  const [open, setOpen] = useW(false);
  const [sent, setSent] = useW(false);
  const [busy, setBusy] = useW(false);
  const [greeted, setGreeted] = useW(false);
  const [form, setForm] = useW({ name: "", company: "", email: "", phone: "", message: "" });
  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  useWE(() => {
    if (open && !greeted) {
      const t = setTimeout(() => setGreeted(true), 650);
      return () => clearTimeout(t);
    }
  }, [open, greeted]);

  const onSubmit = async (e) => {
    e.preventDefault();
    if (!form.message.trim() && !form.name.trim()) return;
    setBusy(true);
    await postContact({
      name: form.name, company: form.company, email: form.email,
      phone_optional: form.phone || null, message: form.message,
      solution_interest: null, source: "staminex_website",
    });
    setBusy(false); setSent(true);
  };

  return (
    <>
      <div className={"cw" + (open ? " cw--open" : "")}>
        <div className="cw__head">
          <span className="cw__avatar"><Icon name="spark" size={18} /></span>
          <div className="cw__headtxt">
            <b>Asistente STAMINEX</b>
            <span><span className="cw__online" /> Responde en minutos</span>
          </div>
          <button className="cw__close" aria-label="Cerrar" onClick={() => setOpen(false)}><Icon name="close" size={18} /></button>
        </div>

        <div className="cw__body">
          {greeted && (
            <div className="cw__msg">
              ¡Hola! 👋 Soy el asistente de STAMINEX. Cuéntanos qué te gustaría automatizar y
              te responderemos pronto. No necesitas registrarte.
            </div>
          )}

          {sent ? (
            <div className="cw__msg cw__msg--ok">
              <span className="cw__okic"><Icon name="check" size={16} stroke={2.6} /></span>
              Gracias. Recibimos tu solicitud. Te responderemos pronto.
            </div>
          ) : greeted ? (
            <form className="cw__form" onSubmit={onSubmit}>
              <div className="cw__grid">
                <input placeholder="Nombre" value={form.name} onChange={set("name")} />
                <input placeholder="Empresa" value={form.company} onChange={set("company")} />
              </div>
              <input placeholder="Correo" type="email" value={form.email} onChange={set("email")} />
              <input placeholder="WhatsApp (opcional)" value={form.phone} onChange={set("phone")} />
              <textarea placeholder="Tu mensaje…" rows={2} value={form.message} onChange={set("message")} />
              <button className="cw__send" type="submit" disabled={busy}>
                {busy ? "Enviando…" : "Enviar"} {!busy && <Icon name="send" size={15} />}
              </button>
            </form>
          ) : (
            <div className="cw__typing"><span /><span /><span /></div>
          )}
        </div>
        <div className="cw__foot">
          <a href={waNumber ? `https://wa.me/${waNumber}?text=${encodeURIComponent("Hola STAMINEX, quiero información sobre automatización para mi negocio.")}` : `https://wa.me/?text=${encodeURIComponent("Hola STAMINEX, quiero información sobre automatización para mi negocio.")}`} target="_blank" rel="noopener">
            <Icon name="whatsapp" size={16} /> Prefiero WhatsApp
          </a>
        </div>
      </div>

      <button className={"cw-launch" + (open ? " is-hidden" : "")} onClick={() => setOpen(true)} aria-label="Abrir chat">
        <Icon name="chat" size={24} />
        <span className="cw-launch__pulse" />
      </button>
    </>
  );
}

function WhatsAppFab({ waNumber }) {
  const msg = encodeURIComponent("Hola STAMINEX, quiero información sobre automatización para mi negocio.");
  const href = waNumber ? `https://wa.me/${waNumber}?text=${msg}` : `https://wa.me/?text=${msg}`;
  return (
    <a className="wa-fab" href={href} target="_blank" rel="noopener" aria-label="Hablar por WhatsApp">
      <Icon name="whatsapp" size={26} />
      <span className="wa-fab__label">Hablar por WhatsApp</span>
    </a>
  );
}

Object.assign(window, { ChatWidget, WhatsAppFab });
