// Join-the-team modal — photographer application form.
// Sends via FormSubmit.co AJAX to the studio inbox. Honeypot + time-gate for bots.

const { useState, useEffect, useRef } = React;

const JT_ENDPOINT = "https://formsubmit.co/ajax/masone@theofficephotographer.com";

const JT_SPECIALTIES = [
  "Architecture & interiors",
  "Portraits & people",
  "Urban & street",
  "Nature & landscape",
  "Timelapse",
  "Video & motion",
  "Drone",
];

const JT_INITIAL = {
  name: "",
  email: "",
  phone: "",
  location: "",
  portfolio: "",
  socials: "",
  years: "",
  travel: "",
  specialties: [],
  kit: "",
  motion: "",
  drone: "",
  insurance: "",
  siteExp: "",
  notes: "",
};

function JTSeg({ options, value, onChange, multi }) {
  const isOn = (o) => (multi ? value.includes(o) : value === o);
  const toggle = (o) => {
    if (multi) onChange(isOn(o) ? value.filter((v) => v !== o) : [...value, o]);
    else onChange(isOn(o) ? "" : o);
  };
  return (
    <div className="cf-seg">
      {options.map((o) => (
        <button
          type="button"
          key={o}
          className={"cf-seg-btn " + (isOn(o) ? "on" : "")}
          onClick={() => toggle(o)}
        >
          {o}
        </button>
      ))}
    </div>
  );
}

function JoinTeamModal({ open, onClose }) {
  const [form, setForm] = useState(JT_INITIAL);
  const [honey, setHoney] = useState("");
  const [status, setStatus] = useState("idle"); // idle | sending | sent | error
  const openedAt = useRef(0);

  useEffect(() => {
    if (open) {
      openedAt.current = Date.now();
      setStatus("idle");
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "";
    }
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  if (!open) return null;

  const set = (k) => (v) => setForm((f) => ({ ...f, [k]: v }));
  const setText = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  const valid =
    form.name.trim() && form.email.trim().includes("@") && form.location.trim() &&
    form.portfolio.trim() && form.years && form.travel &&
    form.specialties.length > 0 && form.kit.trim();

  const submit = async (e) => {
    e.preventDefault();
    if (!valid || status === "sending") return;

    // Spam gates: hidden honeypot filled, or form submitted inhumanly fast.
    // Bots get a fake success; nothing is sent.
    if (honey.trim() || Date.now() - openedAt.current < 4000) {
      setStatus("sent");
      return;
    }

    setStatus("sending");
    try {
      const res = await fetch(JT_ENDPOINT, {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify({
          _subject: `Photographer application — ${form.name}`,
          _template: "table",
          _captcha: "false",
          "Full name": form.name,
          "Email": form.email,
          "Phone": form.phone || "—",
          "Based in": form.location,
          "Portfolio": form.portfolio,
          "Socials": form.socials || "—",
          "Years professional": form.years,
          "Willing to travel": form.travel,
          "Specialties": form.specialties.join(", "),
          "Kit": form.kit,
          "Video / timelapse": form.motion || "—",
          "Drone licence": form.drone || "—",
          "Insurance": form.insurance || "—",
          "Construction site experience": form.siteExp || "—",
          "Availability & notes": form.notes || "—",
        }),
      });
      const data = await res.json();
      if (res.ok && data && String(data.success) === "true") setStatus("sent");
      else setStatus("error");
    } catch (err) {
      setStatus("error");
    }
  };

  return (
    <div className="modal-overlay" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal-panel" role="dialog" aria-modal="true" aria-label="Join our team">
        <button className="modal-close" onClick={onClose} aria-label="Close">&times;</button>

        {status === "sent" ? (
          <div className="contact-form contact-form-sent" style={{ margin: 0 }}>
            <div className="contact-form-mark">&#10003;</div>
            <h3>Thanks, we&rsquo;ve got it.</h3>
            <p>
              Your application is in front of the studio. We review every submission personally and
              we&rsquo;ll be in touch if there&rsquo;s a fit — usually within a couple of weeks.
            </p>
            <button className="cta-secondary" onClick={onClose}>Close</button>
          </div>
        ) : (
          <>
            <div className="section-label">Photographers</div>
            <h2 className="modal-title">Join our team.</h2>
            <p className="modal-intro">
              The Office Photographer started as one photographer and a timelapse camera. It&rsquo;s now a
              studio with a constant stream of enquiries for finished-workspace shoots across the country —
              more than any one crew can cover. If you have strong experience in architecture, portrait,
              nature or urban photography, you own your equipment, and you like to travel, tell us about
              yourself below. Every application gets read by a photographer, not a recruiter.
            </p>

            <form className="contact-form" style={{ margin: 0 }} onSubmit={submit}>
              {/* Honeypot — humans never see this field */}
              <div className="jt-honey" aria-hidden="true">
                <label>
                  Leave this field empty
                  <input type="text" tabIndex="-1" autoComplete="off" value={honey} onChange={(e) => setHoney(e.target.value)} />
                </label>
              </div>

              <div className="cf-row">
                <label className="cf-field">
                  <span>Full name</span>
                  <input type="text" value={form.name} onChange={setText("name")} placeholder="Your name" required />
                </label>
                <label className="cf-field">
                  <span>Email</span>
                  <input type="email" value={form.email} onChange={setText("email")} placeholder="you@example.com" required />
                </label>
              </div>

              <div className="cf-row">
                <label className="cf-field">
                  <span>Phone <em>optional</em></span>
                  <input type="tel" value={form.phone} onChange={setText("phone")} placeholder="Best number" />
                </label>
                <label className="cf-field">
                  <span>Based in</span>
                  <input type="text" value={form.location} onChange={setText("location")} placeholder="City, state" required />
                </label>
              </div>

              <div className="cf-row">
                <label className="cf-field">
                  <span>Portfolio or website</span>
                  <input type="text" value={form.portfolio} onChange={setText("portfolio")} placeholder="yoursite.com" required />
                </label>
                <label className="cf-field">
                  <span>Instagram or socials <em>optional</em></span>
                  <input type="text" value={form.socials} onChange={setText("socials")} placeholder="@handle" />
                </label>
              </div>

              <div className="cf-field">
                <span>Years shooting professionally</span>
                <JTSeg options={["1–3", "3–5", "5–10", "10+"]} value={form.years} onChange={set("years")} />
              </div>

              <div className="cf-field">
                <span>Specialties <em>pick all that apply</em></span>
                <JTSeg options={JT_SPECIALTIES} value={form.specialties} onChange={set("specialties")} multi />
              </div>

              <div className="cf-field">
                <span>Your kit <em>bodies, key lenses, lighting</em></span>
                <textarea rows="3" value={form.kit} onChange={setText("kit")} placeholder="e.g. Sony A7R V, 16-35 f/2.8, 24-70 f/2.8, tilt-shift, Profoto B10s…" required />
              </div>

              <div className="cf-row">
                <div className="cf-field">
                  <span>Video &amp; timelapse capability</span>
                  <JTSeg options={["Stills only", "Stills + video", "Full timelapse rig"]} value={form.motion} onChange={set("motion")} />
                </div>
                <div className="cf-field">
                  <span>Drone licence</span>
                  <JTSeg options={["Licensed", "Not licensed"]} value={form.drone} onChange={set("drone")} />
                </div>
              </div>

              <div className="cf-row">
                <div className="cf-field">
                  <span>Public liability insurance</span>
                  <JTSeg options={["Insured", "Will arrange"]} value={form.insurance} onChange={set("insurance")} />
                </div>
                <div className="cf-field">
                  <span>Active construction site experience</span>
                  <JTSeg options={["Yes", "Not yet"]} value={form.siteExp} onChange={set("siteExp")} />
                </div>
              </div>

              <div className="cf-field">
                <span>Willing to travel</span>
                <JTSeg options={["My region", "Interstate", "Anywhere"]} value={form.travel} onChange={set("travel")} />
              </div>

              <div className="cf-field">
                <span>Availability &amp; anything else <em>optional</em></span>
                <textarea rows="3" value={form.notes} onChange={setText("notes")} placeholder="Notice you need, days you shoot, and anything we should know." />
              </div>

              <div className="cf-actions">
                <button className="cta-primary" type="submit" disabled={!valid || status === "sending"}>
                  {status === "sending" ? "Sending…" : "Submit application"}
                </button>
                <div className="cf-fineprint">
                  Goes straight to the studio. No agencies, no middlemen.
                </div>
              </div>

              {status === "error" && (
                <div className="jt-error">
                  Something went wrong sending that. Try again, or email us directly at{" "}
                  <a href="mailto:masone@theofficephotographer.com">masone@theofficephotographer.com</a>.
                </div>
              )}
            </form>
          </>
        )}
      </div>
    </div>
  );
}

window.JoinTeamModal = JoinTeamModal;
