/* ============================================================
   JNW Camp Maintenance — Customer portal (submit + track)
   Talks to the API via props.onSubmit; tracked tickets are passed
   in from the report-app shell (reduced, public-safe shape).
   ============================================================ */
function CustomerView({ onSubmit, onTrack, myTickets = [], trackEmail = "" }) {
  const empty = { title: "", property: "", unit: "", category: "Plumbing", priority: "medium", description: "", name: "", role: "Leader", troop: "", email: "", phone: "" };
  const [form, setForm] = useState(empty);
  const [photos, setPhotos] = useState([]);
  const [errors, setErrors] = useState({});
  const [submitted, setSubmitted] = useState(null); // { id, name }
  const [busy, setBusy] = useState(false);
  const [submitError, setSubmitError] = useState("");
  const fileRef = useRef(null);

  // Track-an-existing-request entry (email or phone, no new ticket needed).
  const [trackOpen, setTrackOpen] = useState(false);
  const [trackInput, setTrackInput] = useState("");
  const [trackBusy, setTrackBusy] = useState(false);
  const [trackError, setTrackError] = useState("");

  async function findRequests() {
    const c = trackInput.trim();
    if (!c) { setTrackError("Enter your email or phone number."); return; }
    setTrackBusy(true); setTrackError("");
    try {
      const list = await onTrack(c);
      if (!list || list.length === 0) setTrackError("No requests found for that contact.");
    } catch (e) {
      setTrackError(e.message || "Couldn't look that up — please try again.");
    } finally {
      setTrackBusy(false);
    }
  }
  const mobile = useIsMobile();
  const col2 = mobile ? "1fr" : "1fr 1fr";

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

  function pickFiles(e) {
    const files = Array.from(e.target.files || []).slice(0, 4 - photos.length);
    files.forEach((file) => {
      const reader = new FileReader();
      reader.onload = () => setPhotos((p) => [...p, { kind: "img", url: reader.result, label: file.name }]);
      reader.readAsDataURL(file);
    });
    e.target.value = "";
  }

  function validate() {
    const er = {};
    if (!form.title.trim()) er.title = "Give your request a short title.";
    if (!form.description.trim()) er.description = "Describe the issue.";
    if (!form.name.trim()) er.name = "We need a contact name.";
    if (form.email.trim() && !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) er.email = "Enter a valid email.";
    if (!form.property.trim()) er.property = "Which camp area?";
    setErrors(er);
    return Object.keys(er).length === 0;
  }

  async function submit() {
    if (busy) return;
    setSubmitError("");
    if (!validate()) return;
    setBusy(true);
    try {
      const name = form.name.trim();
      const t = await onSubmit({ form, photos });
      setSubmitted({ id: t.id, name });
      setForm(empty); setPhotos([]); setErrors({});
      window.scrollTo({ top: 0, behavior: "smooth" });
    } catch (e) {
      setSubmitError(e.message || "Something went wrong submitting your request. Please try again.");
    } finally {
      setBusy(false);
    }
  }

  const fieldStyle = (k) => ({
    fontFamily: "inherit", fontSize: 15, padding: "0 14px", height: 50, width: "100%", boxSizing: "border-box",
    border: "1px solid " + (errors[k] ? "#FF5E2E" : "#E6E6E6"), borderRadius: 8, background: "#fff", color: "#16331E", outline: "none",
    transition: "border-color 120ms, box-shadow 120ms",
  });
  const labelStyle = { fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: 13, color: "#16331E", marginBottom: 6, display: "block" };

  return (
    <div style={{ display: "grid", gridTemplateColumns: mobile ? "1fr" : "minmax(0, 380px) minmax(0, 1fr)", height: "100%" }}>
      {/* Left brand panel */}
      <aside style={{ display: mobile ? "none" : "block", background: "#16331E", color: "#fff", padding: "44px 40px", position: "relative", overflow: "hidden" }}>
        <div style={{ position: "absolute", right: -70, bottom: -70, opacity: 0.06, pointerEvents: "none" }}>
          <BrandMark size={300} color="#6FA07C" />
        </div>
        <div style={{ position: "relative", zIndex: 1, display: "flex", flexDirection: "column", height: "100%" }}>
          <BrandLockup tone="light" iconColor="#6FA07C" />
          <div style={{ marginTop: 56 }}>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 40, lineHeight: 1.05, letterSpacing: "-0.025em" }}>
              Report a maintenance issue at camp.
            </div>
            <p style={{ marginTop: 18, fontSize: 16, lineHeight: 1.5, color: "rgba(255,255,255,0.72)", maxWidth: 300 }}>
              Tell us what needs fixing and the ranger crew will take it from there. Most requests are triaged within one business day.
            </p>
          </div>
          <div style={{ marginTop: "auto", paddingTop: 40, display: "flex", flexDirection: "column", gap: 16 }}>
            {[
              { icon: "list-checks", t: "Describe it once", s: "Photos help us come prepared." },
              { icon: "users", t: "We assign a ranger", s: "Matched by trade and load." },
              { icon: "trending-up", t: "Track to done", s: "Watch status update live." },
            ].map((x) => (
              <div key={x.t} style={{ display: "flex", gap: 13, alignItems: "flex-start" }}>
                <div style={{ width: 36, height: 36, borderRadius: 9, background: "rgba(111,160,124,0.18)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                  <Icon name={x.icon} size={17} color="#6FA07C" />
                </div>
                <div>
                  <div style={{ fontSize: 14, fontWeight: 600, fontFamily: "var(--font-display)" }}>{x.t}</div>
                  <div style={{ fontSize: 12.5, color: "rgba(255,255,255,0.6)" }}>{x.s}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </aside>

      {/* Right content */}
      <main style={{ background: "#F2F2F2", padding: mobile ? "22px 16px" : "44px 48px", overflowY: "auto", minHeight: 0 }}>
        <div style={{ maxWidth: 720, margin: "0 auto" }}>
          {submitted && (
            <div style={{ background: "#E6F6EC", border: "1px solid #B8E6C9", borderRadius: 12, padding: "18px 20px", marginBottom: 28, display: "flex", gap: 14, alignItems: "flex-start" }}>
              <Icon name="check-circle" size={26} color="#05873C" />
              <div>
                <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 17, color: "#05873C" }}>Request {submitted.id} received</div>
                <div style={{ fontSize: 14, color: "#0c5a30", marginTop: 3 }}>Thanks, {submitted.name.split(" ")[0]}. We've logged your request and will assign a crew member shortly.{trackEmail ? " Track its status above." : ""}</div>
              </div>
            </div>
          )}

          {/* Track an existing request — no new ticket needed */}
          <div style={{ marginBottom: 22 }}>
            {!trackOpen ? (
              <button type="button" onClick={() => setTrackOpen(true)} style={{
                display: "inline-flex", alignItems: "center", gap: 8, padding: "11px 16px", borderRadius: 10,
                border: "1px solid #E6E6E6", background: "#fff", cursor: "pointer", fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: 13.5, color: "#16331E",
              }}>
                <Icon name="search" size={15} color="#2F6B3A" />Track a request you already submitted
              </button>
            ) : (
              <div style={{ background: "#fff", border: "1px solid #E6E6E6", borderRadius: 12, padding: 16, boxShadow: "var(--shadow-sm)" }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
                  <label style={{ ...labelStyle, marginBottom: 0 }}>Track your requests by email or phone</label>
                  <button type="button" onClick={() => { setTrackOpen(false); setTrackError(""); }} style={{ border: "none", background: "transparent", cursor: "pointer", color: "#9AA3A5", display: "flex" }}><Icon name="x" size={16} color="#9AA3A5" /></button>
                </div>
                <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                  <input value={trackInput} onChange={(e) => setTrackInput(e.target.value)} placeholder="you@email.com or (555) 555-5555"
                    onKeyDown={(e) => e.key === "Enter" && findRequests()} onFocus={focusRing} onBlur={blurRing}
                    style={{ ...fieldStyle(""), flex: 1, minWidth: 180 }} />
                  <Button kind="primary" icon="search" onClick={findRequests} disabled={trackBusy}>{trackBusy ? "Searching…" : "Find"}</Button>
                </div>
                {trackError && <FieldError msg={trackError} />}
              </div>
            )}
          </div>

          {/* Your requests (results) */}
          {myTickets.length > 0 && (
            <div style={{ marginBottom: 28 }}>
              <div style={{ display: "flex", alignItems: "baseline", gap: 10, marginBottom: 14 }}>
                <h3 style={{ margin: 0, fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 18, letterSpacing: "-0.02em", color: "#16331E" }}>Your requests</h3>
                <span style={{ fontSize: 13, color: "#515151" }}>{trackEmail}</span>
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                {myTickets.map((t) => (
                  <div key={t.id} style={{ background: "#fff", border: "1px solid #E6E6E6", borderRadius: 12, padding: "16px 18px", display: "flex", alignItems: "center", gap: 16 }}>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
                        <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "#9AA3A5" }}>{t.id}</span>
                        <PriorityChip priority={t.priority} compact />
                      </div>
                      <div style={{ fontWeight: 600, fontSize: 15, color: "#16331E", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{t.title}</div>
                      <div style={{ fontSize: 12.5, color: "#515151", marginTop: 3 }}>
                        {t.assigneeName ? "Assigned to " + t.assigneeName : "Awaiting assignment"} · Updated {timeAgo(t.updatedAt)}
                      </div>
                    </div>
                    <StatusPill status={t.status} />
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Form card */}
          <div style={{ background: "#fff", borderRadius: 16, border: "1px solid #E6E6E6", boxShadow: "var(--shadow-sm)", overflow: "hidden" }}>
            <div style={{ padding: "22px 28px", borderBottom: "1px solid #F2F2F2" }}>
              <h2 style={{ margin: 0, fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 22, letterSpacing: "-0.02em", color: "#16331E" }}>New maintenance request</h2>
              <p style={{ margin: "4px 0 0", fontSize: 13.5, color: "#515151" }}>Fields marked with an asterisk are required.</p>
            </div>
            <div style={{ padding: 28, display: "flex", flexDirection: "column", gap: 20 }}>
              <div>
                <label style={labelStyle}>Issue title *</label>
                <input style={fieldStyle("title")} value={form.title} placeholder="e.g. Leaking faucet in the Dining Hall"
                  onChange={(e) => set("title", e.target.value)} onFocus={focusRing} onBlur={blurRing} />
                {errors.title && <FieldError msg={errors.title} />}
              </div>

              <div style={{ display: "grid", gridTemplateColumns: mobile ? "1fr" : "1fr 140px", gap: 16 }}>
                <div>
                  <label style={labelStyle}>Camp area *</label>
                  <input style={fieldStyle("property")} value={form.property} placeholder="Base Camp, Cub Country…"
                    onChange={(e) => set("property", e.target.value)} onFocus={focusRing} onBlur={blurRing} />
                  {errors.property && <FieldError msg={errors.property} />}
                </div>
                <div>
                  <label style={labelStyle}>Site / building</label>
                  <input style={fieldStyle("unit")} value={form.unit} placeholder="Health Lodge, Campsite Birch…"
                    onChange={(e) => set("unit", e.target.value)} onFocus={focusRing} onBlur={blurRing} />
                </div>
              </div>

              <div style={{ display: "grid", gridTemplateColumns: col2, gap: 16 }}>
                <div>
                  <label style={labelStyle}>Category</label>
                  <div style={{ position: "relative" }}>
                    <select style={{ ...fieldStyle("category"), appearance: "none", cursor: "pointer" }} value={form.category} onChange={(e) => set("category", e.target.value)} onFocus={focusRing} onBlur={blurRing}>
                      {WOData.CATEGORIES.map((c) => <option key={c} value={c}>{c}</option>)}
                    </select>
                    <Icon name="chevron-down" size={16} color="#515151" style={{ position: "absolute", right: 14, top: 17, pointerEvents: "none" }} />
                  </div>
                </div>
                <div>
                  <label style={labelStyle}>Urgency</label>
                  <div style={{ display: "flex", gap: 6 }}>
                    {WOData.PRIORITIES.slice().reverse().map((p) => {
                      const active = form.priority === p.id;
                      return (
                        <button key={p.id} type="button" onClick={() => set("priority", p.id)} style={{
                          flex: 1, height: 50, borderRadius: 8, cursor: "pointer", fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: 12.5,
                          border: "1px solid " + (active ? p.color : "#E6E6E6"), background: active ? p.color + "1A" : "#fff", color: active ? p.color : "#515151",
                          transition: "all 120ms",
                        }}>{p.label}</button>
                      );
                    })}
                  </div>
                </div>
              </div>

              <div>
                <label style={labelStyle}>Describe the issue *</label>
                <textarea value={form.description} placeholder="What's happening, where, and since when? Any access notes for the crew?"
                  onChange={(e) => set("description", e.target.value)} onFocus={focusRing} onBlur={blurRing}
                  style={{ ...fieldStyle("description"), height: 110, padding: "12px 14px", resize: "vertical", lineHeight: 1.5 }} />
                {errors.description && <FieldError msg={errors.description} />}
              </div>

              {/* Photos */}
              <div>
                <label style={labelStyle}>Photos <span style={{ color: "#9AA3A5", fontWeight: 400 }}>· up to 4, optional</span></label>
                <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
                  {photos.map((p, i) => (
                    <div key={i} style={{ position: "relative" }}>
                      <PhotoThumb photo={p} size={72} />
                      <button type="button" onClick={() => setPhotos((arr) => arr.filter((_, j) => j !== i))} style={{
                        position: "absolute", top: -7, right: -7, width: 22, height: 22, borderRadius: "50%", border: "none", background: "#16331E", color: "#fff",
                        display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", boxShadow: "var(--shadow-sm)",
                      }}><Icon name="x" size={12} /></button>
                    </div>
                  ))}
                  {photos.length < 4 && (
                    <button type="button" onClick={() => fileRef.current.click()} style={{
                      width: 72, height: 72, borderRadius: 8, border: "1.5px dashed #C5CDCF", background: "#FAFBFB", cursor: "pointer",
                      display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 4, color: "#515151",
                    }}>
                      <Icon name="camera" size={20} color="#2F6B3A" />
                      <span style={{ fontSize: 10.5, fontWeight: 600 }}>Add</span>
                    </button>
                  )}
                  <input ref={fileRef} type="file" accept="image/*" multiple onChange={pickFiles} style={{ display: "none" }} />
                </div>
              </div>

              <div style={{ height: 1, background: "#F2F2F2", margin: "2px 0" }}></div>

              <div style={{ display: "grid", gridTemplateColumns: col2, gap: 16 }}>
                <div>
                  <label style={labelStyle}>Your name *</label>
                  <input style={fieldStyle("name")} value={form.name} placeholder="Full name"
                    onChange={(e) => set("name", e.target.value)} onFocus={focusRing} onBlur={blurRing} />
                  {errors.name && <FieldError msg={errors.name} />}
                </div>
                <div>
                  <label style={labelStyle}>I am a…</label>
                  <div style={{ position: "relative" }}>
                    <select style={{ ...fieldStyle("role"), appearance: "none", cursor: "pointer" }} value={form.role} onChange={(e) => set("role", e.target.value)} onFocus={focusRing} onBlur={blurRing}>
                      {["Scout", "Leader", "Parent", "Staff", "Other"].map((r) => <option key={r} value={r}>{r}</option>)}
                    </select>
                    <Icon name="chevron-down" size={16} color="#515151" style={{ position: "absolute", right: 14, top: 17, pointerEvents: "none" }} />
                  </div>
                </div>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: col2, gap: 16 }}>
                <div>
                  <label style={labelStyle}>Email <span style={{ color: "#9AA3A5", fontWeight: 400 }}>· optional, used to track your request</span></label>
                  <input style={fieldStyle("email")} value={form.email} placeholder="you@email.com"
                    onChange={(e) => set("email", e.target.value)} onFocus={focusRing} onBlur={blurRing} />
                  {errors.email && <FieldError msg={errors.email} />}
                </div>
                <div>
                  <label style={labelStyle}>Troop / Pack <span style={{ color: "#9AA3A5", fontWeight: 400 }}>· optional</span></label>
                  <input style={fieldStyle("troop")} value={form.troop} placeholder="e.g. Troop 12"
                    onChange={(e) => set("troop", e.target.value)} onFocus={focusRing} onBlur={blurRing} />
                </div>
              </div>
              <div style={{ maxWidth: 320 }}>
                <label style={labelStyle}>Phone <span style={{ color: "#9AA3A5", fontWeight: 400 }}>· optional</span></label>
                <input style={fieldStyle("phone")} value={form.phone} placeholder="(555) 555-5555"
                  onChange={(e) => set("phone", e.target.value)} onFocus={focusRing} onBlur={blurRing} />
              </div>
            </div>
            <div style={{ padding: mobile ? "16px 18px" : "18px 28px", background: "#FAFBFB", borderTop: "1px solid #F2F2F2", display: "flex", flexWrap: "wrap", gap: 12, justifyContent: "space-between", alignItems: "center" }}>
              {submitError
                ? <span style={{ fontSize: 12.5, color: "#FF5E2E", fontWeight: 600, display: "inline-flex", alignItems: "center", gap: 5 }}><Icon name="alert-triangle" size={13} color="#FF5E2E" />{submitError}</span>
                : <span style={{ fontSize: 12.5, color: "#9AA3A5" }}>Add your email or phone to track this request's status.</span>}
              <Button kind="primary" iconRight="arrow-right" onClick={submit} disabled={busy}>{busy ? "Submitting…" : "Submit request"}</Button>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
}

function FieldError({ msg }) {
  return <div style={{ display: "flex", alignItems: "center", gap: 5, marginTop: 6, color: "#FF5E2E", fontSize: 12.5, fontWeight: 500 }}>
    <Icon name="alert-triangle" size={12} color="#FF5E2E" /> {msg}
  </div>;
}
function focusRing(e) { e.target.style.boxShadow = "0 0 0 3px rgba(47,107,58,0.15)"; }
function blurRing(e) { e.target.style.boxShadow = "none"; }

Object.assign(window, { CustomerView });
