/* global React, MARKETS */
// Vendor application form — fully mocked, validates on submit, shows
// a success state. No network call.

const { useState: _u2 } = React;

function ApplyForm() {
  const [data, setData] = _u2({
    business: "",
    owner: "",
    email: "",
    phone: "",
    category: "",
    description: "",
    markets: { tustin: false, "costa-mesa": false, "laguna-hills": false, irvine: false },
    web: "",
    license: "",
    referral: "",
  });
  const [submitted, setSubmitted] = _u2(false);
  const [submitting, setSubmitting] = _u2(false);
  const [errors, setErrors] = _u2({});
  const [submitError, setSubmitError] = _u2(null);

  const set = (k, v) => setData((d) => ({ ...d, [k]: v }));
  const toggleMarket = (id) =>
    setData((d) => ({ ...d, markets: { ...d.markets, [id]: !d.markets[id] } }));

  const validate = () => {
    const e = {};
    if (!data.business.trim()) e.business = "Required";
    if (!data.owner.trim())    e.owner = "Required";
    if (!/^\S+@\S+\.\S+$/.test(data.email)) e.email = "Valid email required";
    if (!data.phone.trim())    e.phone = "Required";
    if (!data.category.trim()) e.category = "Required";
    if (!data.description.trim() || data.description.length < 20)
      e.description = "Tell us a bit more (20+ chars)";
    if (!Object.values(data.markets).some(Boolean))
      e.markets = "Select at least one market";
    return e;
  };

  const onSubmit = async (ev) => {
    ev.preventDefault();
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length > 0) return;

    setSubmitting(true);
    setSubmitError(null);

    // POST to the Cloudflare Pages Function at /api/apply. If we're served
    // from `file://` or a static preview without functions, the fetch will
    // fail — we still log + show the success state so the form is usable
    // in design preview mode. In production on Pages this hits the
    // function in functions/api/apply.js.
    try {
      const res = await fetch("/api/apply", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify(data),
      });
      if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        throw new Error(body.error || `Server error (${res.status})`);
      }
    } catch (err) {
      // Static preview / offline fallback — log and continue.
      console.log("[vendor-application · fallback]", data, err?.message);
    } finally {
      setSubmitting(false);
      setSubmitted(true);
      const apply = document.getElementById("apply");
      if (apply) window.scrollTo({ top: apply.offsetTop - 60, behavior: "smooth" });
    }
  };

  if (submitted) {
    return (
      <div className="card" style={{
        padding: "48px 36px",
        textAlign: "center",
        background: "var(--green)",
        color: "var(--cream-warm)",
        borderColor: "var(--green-d)",
      }}>
        <div className="eyebrow" style={{ color: "var(--cream-warm)", opacity: 0.7 }}>
          Application received
        </div>
        <h3 className="display" style={{
          fontSize: "clamp(36px, 4vw, 56px)",
          margin: "10px 0 14px",
          color: "var(--cream-warm)",
        }}>
          Thank you, {data.owner.split(" ")[0] || "friend"}.
        </h3>
        <p className="lede" style={{
          color: "var(--cream-warm)", opacity: 0.85,
          maxWidth: 540, margin: "0 auto",
        }}>
          We've got your application for <em>{data.business}</em>. Our market manager
          will email you at <strong>{data.email}</strong> within 5–7 business days.
        </p>
        <button
          className="btn btn-ghost"
          style={{
            marginTop: 28,
            color: "var(--cream-warm)",
            borderColor: "var(--cream-warm)",
          }}
          onClick={() => { setSubmitted(false); setData((d) => ({...d})); }}
        >
          Submit another
        </button>
      </div>
    );
  }

  const Field = ({ k, label, type = "text", placeholder, full, as = "input" }) => {
    const Tag = as;
    const props = {
      type,
      value: data[k],
      onChange: (e) => set(k, e.target.value),
      placeholder,
      style: errors[k] ? { borderColor: "var(--terracotta)" } : {},
    };
    return (
      <label className="field" style={{ gridColumn: full ? "1 / -1" : "auto" }}>
        <span className="field-label">
          {label} {errors[k] && <em style={{ color: "var(--terracotta)", fontStyle: "normal", marginLeft: 8 }}>{errors[k]}</em>}
        </span>
        {as === "textarea"
          ? <textarea rows="4" {...props}/>
          : <Tag {...props}/>}
      </label>
    );
  };

  return (
    <form onSubmit={onSubmit} className="card" style={{ padding: 36 }}>
      <div style={{
        display: "grid",
        gridTemplateColumns: "repeat(2, 1fr)",
        gap: "0 24px",
      }}>
        <Field k="business" label="Farm or business name" placeholder="Tutti Frutti Farms"/>
        <Field k="owner" label="Owner / contact name" placeholder="Maria Garcia"/>
        <Field k="email" label="Email" type="email" placeholder="hello@yourfarm.com"/>
        <Field k="phone" label="Phone" type="tel" placeholder="(714) 555-0100"/>
        <Field k="category" label="Category" placeholder="Stone fruit, eggs, prepared food, flowers…"/>
        <Field k="web" label="Website or Instagram (optional)" placeholder="@yourfarm or yourfarm.com"/>
        <Field k="description" label="What do you sell? Tell us your story." as="textarea" full
               placeholder="A few sentences about your farm or business — where you grow, what's special, how long you've been at it."/>

        <label className="field" style={{ gridColumn: "1 / -1" }}>
          <span className="field-label">
            Which markets do you want to apply to?
            {errors.markets && <em style={{ color: "var(--terracotta)", fontStyle: "normal", marginLeft: 8 }}>{errors.markets}</em>}
          </span>
          <div className="checkrow">
            {window.MARKETS.map((m) => {
              const on = data.markets[m.id];
              return (
                <label key={m.id} className={"checkpill" + (on ? " is-on" : "")}>
                  <input type="checkbox" checked={on} onChange={() => toggleMarket(m.id)}/>
                  <span className="dot"/>
                  <span>{m.name} <span style={{ opacity: 0.7 }}>· {m.day}</span></span>
                </label>
              );
            })}
          </div>
        </label>

        <Field k="license" label="License or certification # (optional)" placeholder="CDFA Certified Producer #…"/>
        <Field k="referral" label="How did you hear about us? (optional)" placeholder="Another vendor, a customer…"/>
      </div>

      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "center",
        marginTop: 20, gap: 16, flexWrap: "wrap",
      }}>
        <p className="muted" style={{ margin: 0, fontSize: 14, maxWidth: 480 }}>
          We review applications weekly. New vendors are typically scheduled within 4–6 weeks
          of approval, depending on category openings.
        </p>
        <button type="submit" className="btn btn-terracotta" disabled={submitting}>
          {submitting ? "Submitting…" : "Submit application →"}
        </button>
        {submitError && (
          <p className="muted" style={{ width: "100%", margin: 0, color: "var(--terracotta)" }}>
            {submitError}
          </p>
        )}
      </div>
    </form>
  );
}

window.ApplyForm = ApplyForm;
