/* global React, Ic, useT */
const { useState } = React;

const SUPPORT_IDS = ["activity", "restaurant", "transport", "language", "planning", "fixer"];
const GROUP_TYPE_IDS = ["stag", "friends", "corp", "sports", "bday", "event", "other"];

function RequestForm() {
  const { t } = useT();

  const STEP_TITLES = [t("form.step.basics"), t("form.step.group"), t("form.step.plan"), t("form.step.review")];
  const GROUP_TYPES = GROUP_TYPE_IDS.map((id) => ({ id, label: t("form.gt." + id) }));
  const SUPPORT_OPTIONS = SUPPORT_IDS.map((id) => ({ id, label: t("form.sup." + id) }));
  const LANGUAGES = [
    { v: "English", label: "English" },
    { v: "Latvian", label: "Latvian" },
    { v: "Any", label: t("form.lang.any") },
  ];

  const [step, setStep] = useState(0);
  const [done, setDone] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [touched, setTouched] = useState({});
  const [data, setData] = useState({
    name: "",
    contact: "",
    date: "",
    size: "",
    type: "",
    activities: "",
    support: [],
    language: "English",
    notes: "",
  });

  const set = (k, v) => setData((d) => ({ ...d, [k]: v }));
  const toggleSupport = (id) =>
    setData((d) => ({
      ...d,
      support: d.support.includes(id) ? d.support.filter((x) => x !== id) : [...d.support, id],
    }));

  // validation per step
  const errors = (() => {
    const e = {};
    if (step === 0) {
      if (!data.name.trim()) e.name = t("form.err.name");
      if (!data.contact.trim()) e.contact = t("form.err.contact_required");
      else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.contact) && !/^[+0-9\s\-()]{7,}$/.test(data.contact))
        e.contact = t("form.err.contact_format");
      if (!data.date) e.date = t("form.err.date");
    }
    if (step === 1) {
      const n = parseInt(data.size, 10);
      if (!data.size) e.size = t("form.err.size_required");
      else if (isNaN(n) || n < 2) e.size = t("form.err.size_number");
      else if (n > 200) e.size = t("form.err.size_max");
      if (!data.type) e.type = t("form.err.type");
    }
    if (step === 2) {
      if (!data.activities.trim()) e.activities = t("form.err.acts");
      if (data.support.length === 0) e.support = t("form.err.support");
    }
    return e;
  })();

  const canAdvance = Object.keys(errors).length === 0;

  const next = () => {
    const fieldsByStep = [
      ["name", "contact", "date"],
      ["size", "type"],
      ["activities", "support"],
    ];
    const fields = fieldsByStep[step] || [];
    setTouched((tt) => ({ ...tt, ...Object.fromEntries(fields.map((f) => [f, true])) }));
    if (!canAdvance) return;
    if (step < 3) setStep(step + 1);
  };
  const back = () => { if (step > 0) setStep(step - 1); };

  const submit = () => {
    setSubmitting(true);
    setTimeout(() => {
      setSubmitting(false);
      setDone(true);
    }, 900);
  };

  const reset = () => {
    setDone(false);
    setStep(0);
    setTouched({});
    setData({ name: "", contact: "", date: "", size: "", type: "", activities: "", support: [], language: "English", notes: "" });
  };

  const groupTypeLabel = data.type ? (GROUP_TYPES.find((g) => g.id === data.type) || {}).label : "";
  const supportLabels = data.support.map((id) => SUPPORT_OPTIONS.find((o) => o.id === id).label).join(", ");

  return (
    <section id="request" className="section form-section" data-screen-label="06 Request">
      <div className="shell">
        <div className="form-grid">
          <div className="form-pitch">
            <span className="eyebrow" style={{ color: "rgba(244,241,232,.6)" }}>
              <span className="dot"></span>{t("form.eyebrow")}
            </span>
            <h2 className="display">
              {t("form.title_l1")}<br/>{t("form.title_l2")}<br/>
              <em>{t("form.title_em")}</em>
            </h2>
            <p>{t("form.p1")}</p>
            <p>{t("form.p2")}</p>
            <div className="form-trust">
              <span><span className="tick"><Ic.check /></span> {t("form.trust1")}</span>
              <span><span className="tick"><Ic.check /></span> {t("form.trust2")}</span>
              <span><span className="tick"><Ic.check /></span> {t("form.trust3")}</span>
            </div>
          </div>

          <div className="form-card">
            {done ? (
              <SuccessPanel data={data} groupTypeLabel={groupTypeLabel} onReset={reset} />
            ) : (
              <>
                <Progress step={step} titles={STEP_TITLES} />

                {step === 0 && (
                  <div className="form-step">
                    <h3>{STEP_TITLES[step]}</h3>
                    <p className="step-hint">{t("form.basics.hint")}</p>

                    <div className={`field${touched.name && errors.name ? " invalid" : ""}`}>
                      <label>{t("form.f.name")}</label>
                      <input
                        type="text"
                        placeholder={t("form.f.name_ph")}
                        value={data.name}
                        onChange={(e) => set("name", e.target.value)}
                        onBlur={() => setTouched((tt) => ({ ...tt, name: true }))}
                      />
                      {touched.name && errors.name && <span className="err">{errors.name}</span>}
                    </div>

                    <div className={`field${touched.contact && errors.contact ? " invalid" : ""}`}>
                      <label>{t("form.f.contact")}</label>
                      <input
                        type="text"
                        placeholder={t("form.f.contact_ph")}
                        value={data.contact}
                        onChange={(e) => set("contact", e.target.value)}
                        onBlur={() => setTouched((tt) => ({ ...tt, contact: true }))}
                      />
                      {touched.contact && errors.contact && <span className="err">{errors.contact}</span>}
                    </div>

                    <div className={`field${touched.date && errors.date ? " invalid" : ""}`}>
                      <label>{t("form.f.date")}</label>
                      <input
                        type="date"
                        value={data.date}
                        onChange={(e) => set("date", e.target.value)}
                        onBlur={() => setTouched((tt) => ({ ...tt, date: true }))}
                      />
                      {touched.date && errors.date && <span className="err">{errors.date}</span>}
                    </div>
                  </div>
                )}

                {step === 1 && (
                  <div className="form-step">
                    <h3>{STEP_TITLES[step]}</h3>
                    <p className="step-hint">{t("form.group.hint")}</p>

                    <div className={`field${touched.size && errors.size ? " invalid" : ""}`}>
                      <label>{t("form.f.size")}</label>
                      <input
                        type="number"
                        min="2"
                        placeholder={t("form.f.size_ph")}
                        value={data.size}
                        onChange={(e) => set("size", e.target.value)}
                        onBlur={() => setTouched((tt) => ({ ...tt, size: true }))}
                      />
                      {touched.size && errors.size && <span className="err">{errors.size}</span>}
                    </div>

                    <div className={`field${touched.type && errors.type ? " invalid" : ""}`}>
                      <label>{t("form.f.type")}</label>
                      <div className="chip-grid">
                        {GROUP_TYPES.map((g) => (
                          <button
                            key={g.id}
                            type="button"
                            className={`chip${data.type === g.id ? " selected" : ""}`}
                            onClick={() => { set("type", g.id); setTouched((tt) => ({ ...tt, type: true })); }}
                          >
                            {g.label}
                          </button>
                        ))}
                      </div>
                      {touched.type && errors.type && <span className="err">{errors.type}</span>}
                    </div>
                  </div>
                )}

                {step === 2 && (
                  <div className="form-step">
                    <h3>{STEP_TITLES[step]}</h3>
                    <p className="step-hint">{t("form.plan.hint")}</p>

                    <div className={`field${touched.activities && errors.activities ? " invalid" : ""}`}>
                      <label>{t("form.f.acts")}</label>
                      <textarea
                        placeholder={t("form.f.acts_ph")}
                        value={data.activities}
                        onChange={(e) => set("activities", e.target.value)}
                        onBlur={() => setTouched((tt) => ({ ...tt, activities: true }))}
                      />
                      {touched.activities && errors.activities && <span className="err">{errors.activities}</span>}
                    </div>

                    <div className={`field${touched.support && errors.support ? " invalid" : ""}`}>
                      <label>{t("form.f.support")} <span style={{ fontWeight: 400, color: "var(--muted)" }}>{t("form.f.support_hint")}</span></label>
                      <div className="choice-grid">
                        {SUPPORT_OPTIONS.map((o) => {
                          const selected = data.support.includes(o.id);
                          return (
                            <button
                              key={o.id}
                              type="button"
                              className={`choice${selected ? " selected" : ""}`}
                              onClick={() => { toggleSupport(o.id); setTouched((tt) => ({ ...tt, support: true })); }}
                            >
                              <span className="check">{selected && <Ic.check />}</span>
                              <span>{o.label}</span>
                            </button>
                          );
                        })}
                      </div>
                      {touched.support && errors.support && <span className="err">{errors.support}</span>}
                    </div>

                    <div className="field">
                      <label>{t("form.f.lang")}</label>
                      <select value={data.language} onChange={(e) => set("language", e.target.value)}>
                        {LANGUAGES.map((l) => <option key={l.v} value={l.v}>{l.label}</option>)}
                      </select>
                    </div>
                  </div>
                )}

                {step === 3 && (
                  <div className="form-step">
                    <h3>{STEP_TITLES[step]}</h3>
                    <p className="step-hint">{t("form.review.hint")}</p>

                    <div className="review">
                      <div className="review-row"><span className="k">{t("form.r.name")}</span><span className="v">{data.name}</span></div>
                      <div className="review-row"><span className="k">{t("form.r.contact")}</span><span className="v">{data.contact}</span></div>
                      <div className="review-row"><span className="k">{t("form.r.date")}</span><span className="v">{data.date}</span></div>
                      <div className="review-row"><span className="k">{t("form.r.size")}</span><span className="v">{data.size} {t("form.r.size_suffix")}</span></div>
                      <div className="review-row"><span className="k">{t("form.r.type")}</span><span className="v">{groupTypeLabel}</span></div>
                      <div className="review-row"><span className="k">{t("form.r.plan")}</span><span className="v">{data.activities}</span></div>
                      <div className="review-row"><span className="k">{t("form.r.support")}</span><span className="v">{supportLabels}</span></div>
                      <div className="review-row"><span className="k">{t("form.r.lang")}</span><span className="v">{data.language === "Any" ? t("form.lang.any") : data.language}</span></div>
                    </div>

                    <div className="field">
                      <label>{t("form.f.notes")} <span style={{ fontWeight: 400, color: "var(--muted)" }}>{t("form.f.notes_hint")}</span></label>
                      <textarea
                        placeholder={t("form.f.notes_ph")}
                        value={data.notes}
                        onChange={(e) => set("notes", e.target.value)}
                      />
                    </div>
                  </div>
                )}

                <div className="form-actions">
                  <button className="form-back" onClick={back} disabled={step === 0}>
                    <Ic.back /> {t("form.back")}
                  </button>
                  {step < 3 ? (
                    <button className="btn btn-accent" onClick={next}>
                      {t("form.continue")} <span className="arrow"><Ic.arrow /></span>
                    </button>
                  ) : (
                    <button className="btn btn-accent" onClick={submit} disabled={submitting}>
                      {submitting ? t("form.submitting") : <>{t("form.submit")} <span className="arrow"><Ic.arrow /></span></>}
                    </button>
                  )}
                </div>
              </>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

function Progress({ step, titles }) {
  return (
    <div className="form-progress">
      {titles.map((label, i) => (
        <React.Fragment key={label + i}>
          <div className={`step-dot${i === step ? " active" : ""}${i < step ? " done" : ""}`}>
            {i < step ? <Ic.check /> : i + 1}
          </div>
          {i < titles.length - 1 && <div className={`step-line${i < step ? " done" : ""}`}></div>}
        </React.Fragment>
      ))}
      <span style={{ marginLeft: 12 }}>{titles[step]}</span>
    </div>
  );
}


function SuccessPanel({ data, groupTypeLabel, onReset }) {
  const { t } = useT();

  React.useEffect(() => {
    fetch("/submitAjax.php", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        ...data,
        groupTypeLabel: groupTypeLabel
      })
    })
        .then(response => response.json())
        .then(result => {
          console.log("submitAjax.php:", result);
        })
        .catch(error => {
          console.error("submitAjax.php error:", error);
        });
  }, []);

  return (
      <div className="success">
        <div className="success-mark"><Ic.bigCheck /></div>
        <h3>{t("form.success.h")}</h3>
        <p>
          {t("form.success.p1")} {data.name.split(" ")[0]} {t("form.success.p2")}{" "}
          {data.contact.includes("@") ? t("form.success.email") : t("form.success.whatsapp")}{" "}
          {t("form.success.p3")} {data.size}-{t("form.success.p4")} {groupTypeLabel.toLowerCase()} {t("form.success.p5")} {data.date}.
        </p>
        <button className="btn btn-ghost" onClick={onReset} style={{ marginTop: 8 }}>
          {t("form.success.again")}
        </button>
      </div>
  );
}

function SuccessPanelOLD({ data, groupTypeLabel, onReset }) {
  const { t } = useT();
  return (
    <div className="success">
      <div className="success-mark"><Ic.bigCheck /></div>
      <h3>{t("form.success.h")}</h3>
      <p>
        {t("form.success.p1")} {data.name.split(" ")[0]} {t("form.success.p2")}{" "}
        {data.contact.includes("@") ? t("form.success.email") : t("form.success.whatsapp")}{" "}
        {t("form.success.p3")} {data.size}-{t("form.success.p4")} {groupTypeLabel.toLowerCase()} {t("form.success.p5")} {data.date}.
      </p>
      <button className="btn btn-ghost" onClick={onReset} style={{ marginTop: 8 }}>
        {t("form.success.again")}
      </button>
    </div>
  );
}

Object.assign(window, { RequestForm });
