// Aanmeldformulier voor CV De Goeie Orde
const { useState: useStateF, useRef: useRefF, useEffect: useEffectF } = React;

const TURNSTILE_SITE_KEY = "0x4AAAAAADXR2JUtqpoemNEn";

function FormSection({ t }) {
  const [data, setData] = useStateF({
    voornaam: "",
    achternaam: "",
    woonplaats: "",
    geboortedatum: "",
    email: "",
    telefoon: "",
    status: "",
    reglement: false,
  });
  const [errors, setErrors] = useStateF({});
  const [submitted, setSubmitted] = useStateF(false);
  const [submitting, setSubmitting] = useStateF(false);
  const [serverError, setServerError] = useStateF("");
  const [hasSig, setHasSig] = useStateF(false);
  const [turnstileToken, setTurnstileToken] = useStateF("");
  const sigRef = useRefF(null);
  const turnstileRef = useRefF(null);
  const turnstileIdRef = useRefF(null);

  const update = (k) => (v) => {
    setData((d) => ({ ...d, [k]: v }));
    setErrors((e) => ({ ...e, [k]: undefined }));
  };

  // ---- Turnstile explicit rendering ----
  // Poll for window.turnstile since the async script may load after this effect runs.
  useEffectF(() => {
    let timer = null;

    const tryRender = () => {
      if (turnstileIdRef.current !== null) return;
      if (!window.turnstile || !turnstileRef.current) {
        timer = setTimeout(tryRender, 50);
        return;
      }
      turnstileIdRef.current = window.turnstile.render(turnstileRef.current, {
        sitekey: TURNSTILE_SITE_KEY,
        callback: (token) => setTurnstileToken(token),
        "expired-callback": () => setTurnstileToken(""),
      });
    };

    tryRender();

    return () => {
      clearTimeout(timer);
      if (turnstileIdRef.current !== null && window.turnstile) {
        window.turnstile.remove(turnstileIdRef.current);
      }
      turnstileIdRef.current = null;
    };
  }, []);

  // ---- signature pad ----
  useEffectF(() => {
    const canvas = sigRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    const dpr = window.devicePixelRatio || 1;
    const resize = () => {
      const rect = canvas.getBoundingClientRect();
      canvas.width = rect.width * dpr;
      canvas.height = rect.height * dpr;
      ctx.scale(dpr, dpr);
      ctx.lineCap = "round";
      ctx.lineJoin = "round";
      ctx.lineWidth = 2.2;
      ctx.strokeStyle = "#2b1810";
    };
    resize();
    window.addEventListener("resize", resize);

    let drawing = false;
    let last = null;

    const getPos = (ev) => {
      const rect = canvas.getBoundingClientRect();
      const touch = ev.touches?.[0];
      return {
        x: (touch ? touch.clientX : ev.clientX) - rect.left,
        y: (touch ? touch.clientY : ev.clientY) - rect.top,
      };
    };
    const start = (ev) => { ev.preventDefault(); drawing = true; last = getPos(ev); setHasSig(true); };
    const move  = (ev) => {
      if (!drawing) return;
      ev.preventDefault();
      const p = getPos(ev);
      ctx.beginPath(); ctx.moveTo(last.x, last.y); ctx.lineTo(p.x, p.y); ctx.stroke();
      last = p;
    };
    const end = () => { drawing = false; };

    canvas.addEventListener("mousedown", start);
    canvas.addEventListener("mousemove", move);
    window.addEventListener("mouseup", end);
    canvas.addEventListener("touchstart", start, { passive: false });
    canvas.addEventListener("touchmove",  move,  { passive: false });
    canvas.addEventListener("touchend",   end);

    return () => {
      window.removeEventListener("resize", resize);
      canvas.removeEventListener("mousedown", start);
      canvas.removeEventListener("mousemove", move);
      window.removeEventListener("mouseup", end);
      canvas.removeEventListener("touchstart", start);
      canvas.removeEventListener("touchmove",  move);
      canvas.removeEventListener("touchend",   end);
    };
  }, []);

  const clearSig = () => {
    const c = sigRef.current;
    c.getContext("2d").clearRect(0, 0, c.width, c.height);
    setHasSig(false);
  };

  const validate = () => {
    const e = {};
    if (!data.voornaam.trim())   e.voornaam     = t.form.errReq;
    if (!data.achternaam.trim()) e.achternaam   = t.form.errReq;
    if (!data.woonplaats.trim()) e.woonplaats   = t.form.errReq;
    if (!data.geboortedatum) {
      e.geboortedatum = t.form.errAge;
    } else {
      const dob = new Date(data.geboortedatum);
      const turns18 = new Date(dob.getFullYear() + 18, dob.getMonth(), dob.getDate());
      if (turns18 > new Date()) e.geboortedatum = t.form.errMinAge;
    }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email.trim())) e.email = t.form.errEmail;
    if (!data.telefoon.trim())   e.telefoon     = t.form.errReq;
    if (!data.status)            e.status       = t.form.errReq;
    if (!hasSig)                 e.signature    = t.form.errSig;
    if (!data.reglement)         e.reglement    = t.form.errAccept;
    if (!turnstileToken)         e.turnstile    = t.form.errTurnstile;
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const submit = async (ev) => {
    ev.preventDefault();
    if (!validate()) return;

    setSubmitting(true);
    setServerError("");
    try {
      const res = await fetch("submit.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          voornaam:                data.voornaam,
          achternaam:              data.achternaam,
          woonplaats:              data.woonplaats,
          geboortedatum:           data.geboortedatum,
          email:                   data.email,
          telefoon:                data.telefoon,
          status:                  data.status,
          signature:               sigRef.current?.toDataURL("image/png") ?? "",
          "cf-turnstile-response": turnstileToken,
        }),
      });
      const result = await res.json();
      if (result.success) {
        setSubmitted(true);
      } else {
        setServerError(result.error || t.form.errServer);
        if (window.turnstile) window.turnstile.reset(turnstileIdRef.current);
        setTurnstileToken("");
      }
    } catch {
      setServerError(t.form.errServer);
      if (window.turnstile) window.turnstile.reset(turnstileIdRef.current);
      setTurnstileToken("");
    } finally {
      setSubmitting(false);
    }
  };

  const reset = () => {
    setData({ voornaam: "", achternaam: "", woonplaats: "", geboortedatum: "", email: "", telefoon: "", status: "", reglement: false });
    clearSig();
    setErrors({});
    setSubmitted(false);
    setServerError("");
    setTurnstileToken("");
    if (window.turnstile) window.turnstile.reset(turnstileIdRef.current);
  };

  return (
    <div className="form-wrap reveal" id="aanmelden">
      <h3>{t.carnaval.formTitle}</h3>
      <p>{t.carnaval.formLead}</p>

      <form className="form-grid" onSubmit={submit} noValidate>
        <div className="form-field">
          <label htmlFor="voornaam">{t.form.voornaam}<span className="req">*</span></label>
          <input id="voornaam" type="text" autoComplete="given-name" value={data.voornaam} onChange={(e) => update("voornaam")(e.target.value)} />
          {errors.voornaam && <span className="err">{errors.voornaam}</span>}
        </div>
        <div className="form-field">
          <label htmlFor="achternaam">{t.form.achternaam}<span className="req">*</span></label>
          <input id="achternaam" type="text" autoComplete="family-name" value={data.achternaam} onChange={(e) => update("achternaam")(e.target.value)} />
          {errors.achternaam && <span className="err">{errors.achternaam}</span>}
        </div>
        <div className="form-field">
          <label htmlFor="woonplaats">{t.form.woonplaats}<span className="req">*</span></label>
          <input id="woonplaats" type="text" autoComplete="address-level2" value={data.woonplaats} onChange={(e) => update("woonplaats")(e.target.value)} />
          {errors.woonplaats && <span className="err">{errors.woonplaats}</span>}
        </div>
        <div className="form-field">
          <label htmlFor="geboortedatum">{t.form.geboortedatum}<span className="req">*</span></label>
          <input id="geboortedatum" type="date" value={data.geboortedatum} onChange={(e) => update("geboortedatum")(e.target.value)} />
          {errors.geboortedatum && <span className="err">{errors.geboortedatum}</span>}
        </div>
        <div className="form-field">
          <label htmlFor="email">{t.form.email}<span className="req">*</span></label>
          <input id="email" type="email" autoComplete="email" value={data.email} onChange={(e) => update("email")(e.target.value)} />
          {errors.email && <span className="err">{errors.email}</span>}
        </div>
        <div className="form-field">
          <label htmlFor="telefoon">{t.form.telefoon}<span className="req">*</span></label>
          <input id="telefoon" type="tel" autoComplete="tel" value={data.telefoon} onChange={(e) => update("telefoon")(e.target.value)} />
          {errors.telefoon && <span className="err">{errors.telefoon}</span>}
        </div>

        <div className="form-field full">
          <label>{t.form.status}<span className="req">*</span></label>
          <div className="radio-row">
            <button type="button"
              className={`radio-pill ${data.status === "nieuw" ? "active" : ""}`}
              onClick={() => update("status")("nieuw")}>
              {t.form.statusNew}
            </button>
            <button type="button"
              className={`radio-pill ${data.status === "meegelopen" ? "active" : ""}`}
              onClick={() => update("status")("meegelopen")}>
              {t.form.statusReturn}
            </button>
          </div>
          {errors.status && <span className="err">{errors.status}</span>}
        </div>

        <div className="form-field full">
          <label>{t.form.handtekening}<span className="req">*</span></label>
          <div className="sigpad-wrap">
            <canvas ref={sigRef} className="sigpad" />
            {!hasSig && <span className="sigpad-hint">{t.form.handtekeningHint}</span>}
            <button type="button" className="sigpad-clear" onClick={clearSig}>{t.form.clear}</button>
          </div>
          {errors.signature && <span className="err">{errors.signature}</span>}
        </div>

        <div className="form-field full">
          <label className="checkbox-row">
            <input type="checkbox" checked={data.reglement} onChange={(e) => update("reglement")(e.target.checked)} />
            <span className="box" aria-hidden="true"></span>
            <span className="text" dangerouslySetInnerHTML={{__html: t.form.reglement}} />
          </label>
          {errors.reglement && <span className="err">{errors.reglement}</span>}
        </div>

        <div className="form-field full">
          <div ref={turnstileRef} />
          {errors.turnstile && <span className="err">{errors.turnstile}</span>}
        </div>

        {serverError && (
          <div className="form-server-error full" style={{gridColumn: "1 / -1"}}>
            {serverError}
          </div>
        )}

        {submitted && (
          <div id="form-toast" className="form-toast full" style={{gridColumn: "1 / -1"}}>
            <strong>{t.form.successTitle}</strong> — {t.form.successBody}
          </div>
        )}

        <div className="form-field full form-submit-row">
          <button type="submit" className="btn btn-primary" disabled={submitting || submitted}>
            {submitting ? t.form.submitting : t.form.submit}
            {!submitting && !submitted && <span className="btn-arrow">→</span>}
          </button>
          <button type="button" className="btn btn-ghost" onClick={reset}>{t.form.reset}</button>
        </div>
      </form>
    </div>
  );
}

window.FormSection = FormSection;
