// Multi-step franchise application form.
// Fields per user spec: Name, Email, Phone, City/State, Preferred location type, Message.

// Google Apps Script web app endpoint that appends submissions to a Google Sheet.
const FORM_WEBHOOK_URL = "https://script.google.com/macros/s/AKfycbzGV--nWehhz1fv-Xi3phJmx2waqcbdLITC_I2D_KNe0A29G_BkpTag2hc7QsdKNio/exec";

async function submitToSheet(payload) {
  // Apps Script web apps don't return CORS headers by default; sending as
  // text/plain (a "simple request") avoids the CORS preflight entirely.
  try {
    await fetch(FORM_WEBHOOK_URL, {
      method: "POST",
      mode: "no-cors",
      headers: { "Content-Type": "text/plain;charset=utf-8" },
      body: JSON.stringify(payload),
    });
    return { ok: true };
  } catch (err) {
    console.error("Form submit failed:", err);
    return { ok: false, error: err.message };
  }
}

function FranchiseForm({ copy, states, lang }) {
  const [step, setStep] = React.useState(0);
  const [done, setDone] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [submitError, setSubmitError] = React.useState(null);
  const [data, setData] = React.useState({
    name: "", email: "", phone: "",
    city: "", state: "",
    experience: "",
    notes: "",
    website: "", // honeypot — must stay empty; bots fill every field they see
  });

  const steps = [
    {
      key: "identity",
      label: lang === "es" ? "Tú" : "You",
      fields: ["name", "email", "phone"],
      validate: () =>
        data.name.trim().length >= 2 &&
        /\S+@\S+\.\S+/.test(data.email) &&
        data.phone.trim().length >= 7,
    },
    {
      key: "place",
      label: lang === "es" ? "Lugar" : "Place",
      fields: ["city", "state"],
      validate: () => data.city.trim().length >= 2 && data.state.length > 0,
    },
    {
      key: "experience",
      label: lang === "es" ? "Experiencia" : "Experience",
      fields: ["experience"],
      validate: () => data.experience.length > 0,
    },
    {
      key: "notes",
      label: lang === "es" ? "Mensaje" : "Message",
      fields: ["notes"],
      validate: () => true,
    },
  ];

  const total = steps.length;
  const current = steps[step];
  const canNext = current.validate();

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

  const next = async () => {
    if (!canNext || submitting) return;
    if (step < total - 1) {
      setStep(step + 1);
      return;
    }
    // Final step — submit to Google Sheet
    setSubmitting(true);
    setSubmitError(null);
    const payload = {
      ...data,
      lang,
      submittedAt: new Date().toISOString(),
      userAgent: navigator.userAgent,
      pageUrl: window.location.href,
    };
    const result = await submitToSheet(payload);
    setSubmitting(false);
    if (result.ok) {
      setDone(true);
    } else {
      setSubmitError(lang === "es"
        ? "No se pudo enviar. Vuelve a intentarlo en un momento."
        : "Could not send. Please try again in a moment."
      );
    }
  };
  const back = () => step > 0 && setStep(step - 1);

  const experienceOptions = [
    { v: "none",  label: lang === "es" ? "Sin experiencia"        : "No experience" },
    { v: "1-3",   label: lang === "es" ? "1–3 años"               : "1–3 years" },
    { v: "3-10",  label: lang === "es" ? "3–10 años"              : "3–10 years" },
    { v: "10+",   label: lang === "es" ? "10+ años"                : "10+ years" },
  ];

  if (done) {
    return (
      <div className="jr-form jr-form--done">
        <div className="jr-form__check">
          <svg viewBox="0 0 60 60" width="60" height="60">
            <circle cx="30" cy="30" r="28" fill="none" stroke="#00BBB6" strokeWidth="3" />
            <path d="M18 31 L27 40 L44 22" fill="none" stroke="#00BBB6" strokeWidth="4" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </div>
        <h3 className="script jr-form__done-title">{copy.formDone}</h3>
        <p className="jr-form__done-sub">{copy.formDoneSub}</p>
        <div className="jr-form__done-summary">
          <strong>{data.name}</strong> · {data.email} · {data.city}, {data.state}
        </div>
      </div>
    );
  }

  return (
    <div className="jr-form">
      {/* Honeypot — hidden from real users (and accessibility tools),
          visible to dumb bots that auto-fill every input. */}
      <div className="jr-form__hp" aria-hidden="true">
        <label>
          Website
          <input
            type="text"
            tabIndex={-1}
            autoComplete="off"
            value={data.website}
            onChange={e => update("website", e.target.value)}
          />
        </label>
      </div>

      {/* Progress */}
      <div className="jr-form__progress">
        <div className="jr-form__progress-info">
          <span className="eyebrow">{copy.formStep} {step + 1} {copy.formOf} {total}</span>
          <span className="jr-form__progress-label">{current.label}</span>
        </div>
        <div className="jr-form__progress-bar">
          {steps.map((s, i) => (
            <div
              key={s.key}
              className={`jr-form__progress-seg ${i <= step ? "is-on" : ""}`}
            />
          ))}
        </div>
      </div>

      {/* Step content */}
      <div className="jr-form__body" key={step}>
        {current.key === "identity" && (
          <div className="jr-form__grid">
            <Field label={copy.formName}>
              <input
                type="text"
                placeholder={copy.formNamePh}
                value={data.name}
                onChange={e => update("name", e.target.value)}
              />
            </Field>
            <Field label={copy.formEmail}>
              <input
                type="email"
                placeholder={copy.formEmailPh}
                value={data.email}
                onChange={e => update("email", e.target.value)}
              />
            </Field>
            <Field label={copy.formPhone}>
              <input
                type="tel"
                placeholder={copy.formPhonePh}
                value={data.phone}
                onChange={e => update("phone", e.target.value)}
              />
            </Field>
          </div>
        )}

        {current.key === "place" && (
          <div className="jr-form__grid">
            <Field label={copy.formCity}>
              <input
                type="text"
                placeholder={copy.formCityPh}
                value={data.city}
                onChange={e => update("city", e.target.value)}
                autoFocus
              />
            </Field>
            <Field label={copy.formState}>
              <select value={data.state} onChange={e => update("state", e.target.value)}>
                <option value="">—</option>
                {states.map(s => <option key={s} value={s}>{s}</option>)}
              </select>
            </Field>
          </div>
        )}

        {current.key === "experience" && (
          <div className="jr-form__experience">
            <p className="jr-form__experience-q">
              {lang === "es"
                ? "¿Cuánta experiencia tienes en el sector restaurantero?"
                : "How much experience do you have in the restaurant industry?"}
            </p>
            <div className="jr-form__experience-grid">
              {experienceOptions.map(opt => (
                <button
                  key={opt.v}
                  type="button"
                  className={`jr-exp ${data.experience === opt.v ? "is-on" : ""}`}
                  onClick={() => update("experience", opt.v)}
                >
                  <span className="jr-exp__label retro">{opt.label}</span>
                </button>
              ))}
            </div>
          </div>
        )}

        {current.key === "notes" && (
          <Field label={copy.formNotes}>
            <textarea
              rows={6}
              placeholder={copy.formNotesPh}
              value={data.notes}
              onChange={e => update("notes", e.target.value)}
              autoFocus
            />
          </Field>
        )}
      </div>

      <div className="jr-form__nav">
        <button
          type="button"
          className="btn btn--ghost"
          onClick={back}
          disabled={step === 0 || submitting}
          style={{ visibility: step === 0 ? "hidden" : "visible" }}
        >
          ← {copy.formBack}
        </button>
        <button
          type="button"
          className="btn"
          onClick={next}
          disabled={!canNext || submitting}
          style={{ opacity: !canNext || submitting ? 0.5 : 1 }}
        >
          {submitting
            ? (lang === "es" ? "Enviando…" : "Sending…")
            : (step === total - 1 ? copy.formSubmit : copy.formNext)}
          {!submitting && step < total - 1 && " →"}
        </button>
      </div>
      {submitError && (
        <div className="jr-form__error" role="alert">
          {submitError}
        </div>
      )}
    </div>
  );
}

function Field({ label, children }) {
  return (
    <label className="jr-field">
      <span className="jr-field__label">{label}</span>
      {children}
    </label>
  );
}

window.FranchiseForm = FranchiseForm;
