/* ENKII — contact / briefing form. window.ENKIIForm */
/* global React */
const { useState: useStateF, useRef: useRefF } = React;

const FORMSPREE = "https://formspree.io/f/meeddpgr";
const WA_NUMBER = "33753966155";

const PROJECT_TYPES = [
  { value: "MVP", label: { fr: "MVP", en: "MVP", pt: "MVP", es: "MVP" } },
  { value: "WebApp + Mobile App", label: { fr: "WebApp + App Mobile", en: "WebApp + Mobile App", pt: "WebApp + App Mobile", es: "WebApp + App Móvil" } },
  { value: "AI Agents", label: { fr: "Agents IA", en: "AI Agents", pt: "Agentes de IA", es: "Agentes de IA" } },
  { value: "Other", label: { fr: "Autre…", en: "Other…", pt: "Outros…", es: "Otros…" } },
];

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

function ContactForm({ lang, ui, accent, accent2 }) {
  const f = ui.form;
  const [vals, setVals] = useStateF({ name: "", phone: "", email: "", project_type: "", message: "" });
  const [errs, setErrs] = useStateF({});
  const [status, setStatus] = useStateF("idle"); // idle | sending | success | error
  const [errMsg, setErrMsg] = useStateF("");
  const formRef = useRefF(null);

  const set = (k) => (e) => {
    const v = e.target.value;
    setVals((p) => ({ ...p, [k]: v }));
    if (errs[k]) setErrs((p) => ({ ...p, [k]: null }));
  };

  const validate = () => {
    const e = {};
    if (!vals.email.trim() || !EMAIL_RE.test(vals.email.trim())) e.email = f.errEmail;
    if (!vals.project_type) e.project_type = f.errType;
    setErrs(e);
    return Object.keys(e).length === 0;
  };

  const submit = async (ev) => {
    ev.preventDefault();
    if (status === "sending") return;
    if (!validate()) return;
    setStatus("sending");
    setErrMsg("");
    try {
      const res = await fetch(FORMSPREE, {
        method: "POST",
        body: new FormData(formRef.current),
        headers: { Accept: "application/json" },
      });
      if (res.ok) {
        setStatus("success");
        setVals({ name: "", phone: "", email: "", project_type: "", message: "" });
        formRef.current.reset();
        if (typeof fbq === "function") fbq("track", "Lead");
        if (typeof gtag === "function") gtag("event", "conversion", { send_to: "AW-18209717908/uc92CNSRrbgcEJT9iOtD", value: 1.0, currency: "EUR" });
      } else {
        let msg = f.errSend;
        try { const d = await res.json(); if (d && d.errors && d.errors[0]) msg = d.errors[0].message; } catch (e) {}
        setStatus("error"); setErrMsg(msg);
      }
    } catch (e) {
      setStatus("error"); setErrMsg(f.errSend);
    }
  };

  const waHref = () => {
    const parts = [f.waText];
    if (vals.project_type) parts.push("[" + vals.project_type + "]");
    if (vals.message) parts.push(vals.message);
    if (vals.name) parts.push("— " + vals.name);
    return "https://wa.me/" + WA_NUMBER + "?text=" + encodeURIComponent(parts.join(" "));
  };

  const count = vals.message.length;

  return (
    <div className="cf-wrap" style={{ "--a": accent, "--a2": accent2 }}>
      <div className="cf-head">
        <h2 className="cf-title">{f.title[lang]}<br /><span style={{ color: accent2 }}>{f.title2[lang]}</span></h2>
        <p className="cf-sub">{f.sub}</p>
        <div className="cf-resp"><span className="cf-resp-dot" />{f.respLabel}</div>
      </div>

      <div className="cf-channels">
        <a className="cf-chan" href={waHref()} target="_blank" rel="noopener">
          <span className="cf-chan-ic" aria-hidden="true">
            <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="M12 2a10 10 0 00-8.6 15l-1.3 4.8 4.9-1.3A10 10 0 1012 2zm5.3 14.2c-.2.6-1.3 1.2-1.8 1.2-.5.1-1 .1-1.7-.1-.4-.1-.9-.3-1.6-.6a9.4 9.4 0 01-3.6-3.2c-.3-.4-.8-1.1-.8-2.1s.5-1.5.7-1.7c.2-.2.4-.3.6-.3h.4c.2 0 .4 0 .5.4l.7 1.6c.1.1.1.3 0 .5l-.3.4-.3.3c-.1.1-.2.3-.1.5a7 7 0 003.2 2.8c.3.1.4.1.6-.1l.6-.8c.2-.2.3-.2.5-.1l1.6.8c.2.1.4.2.4.3v.9z" /></svg>
          </span>
          <span className="cf-chan-txt"><b>{f.whatsapp}</b><span>+33 753 966 155</span></span>
        </a>
        <a className="cf-chan" href="mailto:info@enkii.fr">
          <span className="cf-chan-ic" aria-hidden="true">
            <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.7"><rect x="3" y="5" width="18" height="14" rx="2" /><path d="M4 7l8 6 8-6" /></svg>
          </span>
          <span className="cf-chan-txt"><b>{f.email}</b><span>info@enkii.fr</span></span>
        </a>
        <div className="cf-chan cf-chan-static">
          <span className="cf-chan-ic" aria-hidden="true">
            <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.7"><path d="M12 21s7-5.7 7-11a7 7 0 10-14 0c0 5.3 7 11 7 11z" /><circle cx="12" cy="10" r="2.5" /></svg>
          </span>
          <span className="cf-chan-txt"><b>{f.location}</b><span>{f.locationVal}</span></span>
        </div>
        <div className="cf-chan cf-chan-static">
          <span className="cf-chan-ic" aria-hidden="true">
            <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.7"><circle cx="12" cy="12" r="9" /><path d="M3 12h18M12 3c2.5 2.5 2.5 15 0 18M12 3c-2.5 2.5-2.5 15 0 18" /></svg>
          </span>
          <span className="cf-chan-txt"><b>{f.langs}</b><span>{f.langsVal}</span></span>
        </div>
      </div>

      {status === "success" ? (
        <div className="cf-success" role="status">
          <span className="cf-success-ic"><svg viewBox="0 0 24 24" width="26" height="26" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5" /></svg></span>
          <p>{f.success}</p>
          <button className="cf-again" onClick={() => setStatus("idle")}>↺</button>
        </div>
      ) : (
        <form ref={formRef} className="cf-form" action={FORMSPREE} method="POST" onSubmit={submit} noValidate>
          <div className="cf-row2">
            <label className="cf-field">
              <span className="cf-label">{f.fName}</span>
              <input type="text" name="name" value={vals.name} onChange={set("name")} autoComplete="name" />
            </label>
            <label className="cf-field">
              <span className="cf-label">{f.fPhone}</span>
              <input type="tel" name="phone" value={vals.phone} onChange={set("phone")} autoComplete="tel" />
            </label>
          </div>
          <label className="cf-field">
            <span className="cf-label">{f.fEmail} <i className="req">*</i></span>
            <input type="email" name="email" required value={vals.email} onChange={set("email")} autoComplete="email"
              className={errs.email ? "err" : ""} aria-invalid={!!errs.email} />
            {errs.email && <span className="cf-err">{errs.email}</span>}
          </label>
          <label className="cf-field">
            <span className="cf-label">{f.fType} <i className="req">*</i></span>
            <div className="cf-select-wrap">
              <select name="project_type" required value={vals.project_type} onChange={set("project_type")}
                className={errs.project_type ? "err" : ""} aria-invalid={!!errs.project_type}>
                <option value="">{f.fTypePh}</option>
                {PROJECT_TYPES.map((p) => <option key={p.value} value={p.value}>{p.label[lang]}</option>)}
              </select>
              <svg className="cf-select-ic" viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M6 9l6 6 6-6" /></svg>
            </div>
            {errs.project_type && <span className="cf-err">{errs.project_type}</span>}
          </label>
          <label className="cf-field">
            <span className="cf-label">{f.fMsg}<b className="cf-count">{count}/1000</b></span>
            <textarea name="message" maxLength="1000" rows="3" value={vals.message} onChange={set("message")} />
          </label>

          {status === "error" && <div className="cf-formerr">{errMsg}</div>}

          <button type="submit" className="cf-submit" disabled={status === "sending"}>
            {status === "sending" ? <><span className="cf-spin" />{f.sending}</> : <>{f.send}<span>→</span></>}
          </button>
        </form>
      )}
    </div>
  );
}

window.ENKIIForm = { ContactForm };
