/* global React */
const { useState: useStateI, useEffect: useEffectI, useRef: useRefI } = React;

/* Web3Forms access keys — one per form, from https://web3forms.com */
const WEB3FORMS_KEYS = {
  events: "0a020f8d-78f4-45e8-985c-da875d225993",
  careers: "4d0c49d5-5c8c-4a1e-b155-b20272843da2"
};

/* InquiryModal — private events inquiry form.
   Uses the existing .dh-modal* styles in index.html. */
function InquiryModal({ open, onClose, mode = "events", role = null }) {
  const isCareers = mode === "careers";
  const [sent, setSent] = useStateI(false);
  const [sending, setSending] = useStateI(false);
  const [failed, setFailed] = useStateI(false);
  const [form, setForm] = useStateI({
    name: "",
    email: "",
    phone: "",
    contact: "Email",
    date: "",
    size: 12,
    space: "Indoor Table",
    occasion: "",
    notes: "",
    role: role || "Server",
    experience: "1–3 yrs",
    availability: "Full-time"
  });

  // Sync role when modal opens with a new role
  useEffectI(() => {
    if (open && role) setForm(f => ({ ...f, role }));
  }, [open, role]);

  // Reset confirmation when modal reopens
  useEffectI(() => { if (open) { setSent(false); setFailed(false); setSending(false); } }, [open]);

  // Close on Escape
  useEffectI(() => {
    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) => (e) => setForm({ ...form, [k]: e.target.value });
  const pick = (k, v) => () => setForm({ ...form, [k]: v });

  const submit = async (e) => {
    e.preventDefault();
    setSending(true);
    setFailed(false);

    const accessKey = isCareers ? WEB3FORMS_KEYS.careers : WEB3FORMS_KEYS.events;

    const payload = isCareers
      ? {
          access_key: accessKey,
          subject: `Career application — ${form.role} (${form.name})`,
          from_name: form.name,
          role: form.role,
          availability: form.availability,
          experience: form.experience,
          name: form.name,
          email: form.email,
          phone: form.phone,
          notes: form.notes
        }
      : {
          access_key: accessKey,
          subject: `Event inquiry — ${form.name || "new inquiry"}`,
          from_name: form.name,
          name: form.name,
          email: form.email,
          phone: form.phone,
          contact: form.contact,
          date: form.date,
          size: form.size,
          space: form.space,
          occasion: form.occasion,
          notes: form.notes
        };

    const data = new FormData();
    Object.keys(payload).forEach((k) => data.append(k, payload[k] ?? ""));
    data.append("botcheck", ""); // honeypot — must stay empty

    try {
      const res = await fetch("https://api.web3forms.com/submit", {
        method: "POST",
        headers: { Accept: "application/json" },
        body: data
      });
      const json = await res.json();
      if (json.success) {
        setSent(true);
      } else {
        setFailed(true);
      }
    } catch (err) {
      setFailed(true);
    } finally {
      setSending(false);
    }
  };

  return (
    <div className="dh-modal" role="dialog" aria-modal="true" aria-labelledby="inquiry-title">
      <div className="dh-modal-scrim" onClick={onClose} />
      <div className="dh-modal-panel">
        <button className="dh-modal-close" aria-label="Close" onClick={onClose}>×</button>

        {sent ? (
          <div className="dh-modal-confirm">
            <div className="dh-plate-spin" aria-hidden="true">
              <svg width="56" height="56" viewBox="0 0 64 64" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
                <path d="M14 34 L28 46 L50 20" />
              </svg>
            </div>
            <h3 className="dh-modal-title" id="inquiry-title">Thank You!</h3>
            <p className="dh-field-help" style={{ fontSize: 15, maxWidth: 360 }}>
              {isCareers
                ? <>Application received for <strong>{form.role}</strong>. We'll be in touch when a position becomes available.</>
                : <>Inquiry received for <strong>{form.name || "your party"}</strong>. We'll be in touch shortly.</>}
            </p>
            <button className="dh-btn dh-btn-ghost" onClick={onClose} style={{ marginTop: 12 }}>Close</button>
          </div>
        ) : failed ? (
          <div className="dh-modal-confirm">
            <h3 className="dh-modal-title" id="inquiry-title">Hmm, that didn't go through.</h3>
            <p className="dh-field-help" style={{ fontSize: 15, maxWidth: 360 }}>
              Please call or text us at <a href="tel:+15615103381">(561) 510-3381</a>, or email{" "}
              <a href="mailto:info@dimisgreekhouse.com">info@dimisgreekhouse.com</a> directly.
            </p>
            <div style={{ display: "flex", gap: 10, marginTop: 12 }}>
              <button className="dh-link" onClick={() => setFailed(false)}>Try again</button>
              <button className="dh-btn dh-btn-ghost" onClick={onClose}>Close</button>
            </div>
          </div>
        ) : isCareers ? (
          <form onSubmit={submit}>
            <h3 className="dh-modal-title" id="inquiry-title">Apply to Dimi's.</h3>
            <p className="dh-field-help" style={{ marginBottom: 18 }}>
              Tell us a little about yourself &mdash; we read every application.
            </p>

            <div className="dh-modal-body">

              {/* role + availability */}
              <div className="dh-fieldgrid">
                <div className="dh-field">
                  <label className="dh-field-label" htmlFor="iq-role">Role</label>
                  <select id="iq-role" className="dh-input" value={form.role} onChange={set("role")}>
                    <option>Server</option>
                    <option>Bartender</option>
                    <option>Host</option>
                    <option>Line Cook</option>
                    <option>Sous Chef</option>
                    <option>Dishwasher</option>
                    <option>Open application</option>
                  </select>
                </div>
                <div className="dh-field">
                  <span className="dh-field-label">Availability</span>
                  <div className="dh-pillrow">
                    {["Full-time", "Part-time", "Either"].map(v => (
                      <button
                        type="button" key={v}
                        className={`dh-pill ${form.availability === v ? "is-on" : ""}`}
                        onClick={pick("availability", v)}
                      >{v}</button>
                    ))}
                  </div>
                </div>
              </div>

              {/* name + contact */}
              <div className="dh-fieldgrid" style={{ marginTop: 6 }}>
                <div className="dh-field dh-field-wide">
                  <label className="dh-field-label" htmlFor="iq-name">Your name</label>
                  <input id="iq-name" className="dh-input" required value={form.name} onChange={set("name")} />
                </div>
                <div className="dh-field">
                  <label className="dh-field-label" htmlFor="iq-email">Email</label>
                  <input id="iq-email" type="email" className="dh-input" required value={form.email} onChange={set("email")} />
                </div>
                <div className="dh-field">
                  <label className="dh-field-label" htmlFor="iq-phone">Phone</label>
                  <input id="iq-phone" type="tel" className="dh-input" required value={form.phone} onChange={set("phone")} />
                </div>
              </div>

              {/* experience */}
              <div className="dh-field" style={{ marginTop: 6 }}>
                <span className="dh-field-label">Restaurant experience</span>
                <div className="dh-pillrow">
                  {["None", "<1 yr", "1–3 yrs", "3–5 yrs", "5+ yrs"].map(v => (
                    <button
                      type="button" key={v}
                      className={`dh-pill ${form.experience === v ? "is-on" : ""}`}
                      onClick={pick("experience", v)}
                    >{v}</button>
                  ))}
                </div>
              </div>

              {/* notes */}
              <div className="dh-field" style={{ marginTop: 6 }}>
                <label className="dh-field-label" htmlFor="iq-notes">
                  Tell us about yourself <span className="dh-field-opt">optional</span>
                </label>
                <textarea
                  id="iq-notes"
                  className="dh-input"
                  rows={3}
                  placeholder="Where you've worked, what you're great at, why Dimi's…"
                  value={form.notes}
                  onChange={set("notes")}
                  style={{ resize: "vertical", minHeight: 88, fontFamily: "var(--font-body)" }}
                />
              </div>

            </div>

            <div className="dh-modal-actions">
              <button type="button" className="dh-link" onClick={onClose}>Cancel</button>
              <button type="submit" className="dh-btn dh-btn-primary" disabled={sending}>
                {sending ? "Sending…" : "Send application"}
              </button>
            </div>
          </form>
        ) : (
          <form onSubmit={submit}>
            <h3 className="dh-modal-title" id="inquiry-title">Tell us about your event.</h3>

            <div className="dh-modal-body">

              {/* name + contact */}
              <div className="dh-fieldgrid">
                <div className="dh-field dh-field-wide">
                  <label className="dh-field-label" htmlFor="iq-name">Your name</label>
                  <input id="iq-name" className="dh-input" required value={form.name} onChange={set("name")} />
                </div>
                <div className="dh-field">
                  <label className="dh-field-label" htmlFor="iq-email">Email</label>
                  <input id="iq-email" type="email" className="dh-input" required value={form.email} onChange={set("email")} />
                </div>
                <div className="dh-field">
                  <label className="dh-field-label" htmlFor="iq-phone">Phone</label>
                  <input id="iq-phone" type="tel" className="dh-input" required value={form.phone} onChange={set("phone")} />
                </div>
              </div>

              {/* preferred contact method */}
              <div className="dh-field" style={{ marginTop: 6 }}>
                <span className="dh-field-label">Preferred contact</span>
                <div className="dh-pillrow">
                  {["Phone", "Email", "Text"].map(v => (
                    <button
                      type="button" key={v}
                      className={`dh-pill ${form.contact === v ? "is-on" : ""}`}
                      onClick={pick("contact", v)}
                    >{v}</button>
                  ))}
                </div>
              </div>

              {/* date */}
              <div className="dh-field" style={{ marginTop: 6 }}>
                <label className="dh-field-label" htmlFor="iq-date">Preferred date</label>
                <input id="iq-date" type="date" className="dh-input" required value={form.date} onChange={set("date")} />
                <p className="dh-field-help">Two weeks ahead is ideal &mdash; we'll try for less.</p>
              </div>

              {/* number of guests */}
              <div className="dh-field" style={{ marginTop: 6 }}>
                <label className="dh-field-label" htmlFor="iq-size">Number of guests</label>
                <input
                  id="iq-size"
                  type="number"
                  className="dh-input"
                  min={8}
                  max={200}
                  step={1}
                  required
                  value={form.size}
                  onChange={(e) => setForm({ ...form, size: e.target.value })}
                  style={{ maxWidth: 160 }}
                />
              </div>

              {/* seating preference */}
              <div className="dh-field" style={{ marginTop: 6 }}>
                <span className="dh-field-label">Seating preference</span>
                <div className="dh-pillrow">
                  {[
                    "Indoor Table",
                    "Patio Table",
                    "Indoor Buy-Out",
                    "Patio Buy-Out",
                    "Full Space Buy-Out"
                  ].map(v => (
                    <button
                      type="button" key={v}
                      className={`dh-pill ${form.space === v ? "is-on" : ""}`}
                      onClick={pick("space", v)}
                    >{v}</button>
                  ))}
                </div>
              </div>

              {/* occasion */}
              <div className="dh-field" style={{ marginTop: 6 }}>
                <label className="dh-field-label" htmlFor="iq-occasion">
                  Occasion <span className="dh-field-opt">optional</span>
                </label>
                <input id="iq-occasion" className="dh-input" placeholder="Birthday, anniversary, work dinner…" value={form.occasion} onChange={set("occasion")} />
              </div>

              {/* notes */}
              <div className="dh-field" style={{ marginTop: 6 }}>
                <label className="dh-field-label" htmlFor="iq-notes">
                  Anything else? <span className="dh-field-opt">optional</span>
                </label>
                <textarea
                  id="iq-notes"
                  className="dh-input"
                  rows={3}
                  placeholder="Dietary notes, drinks, music, surprises…"
                  value={form.notes}
                  onChange={set("notes")}
                  style={{ resize: "vertical", minHeight: 72, fontFamily: "var(--font-body)" }}
                />
              </div>

            </div>

            <div className="dh-modal-actions">
              <button type="button" className="dh-link" onClick={onClose}>Cancel</button>
              <button type="submit" className="dh-btn dh-btn-primary" disabled={sending}>
                {sending ? "Sending…" : "Send inquiry"}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

window.InquiryModal = InquiryModal;
