/* Testimonials.jsx -- public submission form (CR #196).
   Visitors share a short story + optional photo about a PPR program. The
   submission lands in JJ's inbox (with the photo attached) and is mirrored
   to the dashboard for the owner to triage. Submissions are NOT shown
   on the public site. */

const FLICKR_HERO_PHOTO = "/img/cr-200-testimonial-hero.jpg";
const MAX_PHOTO_BYTES = 5 * 1024 * 1024; // 5 MB raw; matches server cap

function TestimonialsPage() {
  const blank = { name: "", email: "", program: "", message: "" };
  const [data, setData] = React.useState(blank);
  const [photo, setPhoto] = React.useState(null); // { dataUrl, filename, sizeKb }
  const [photoErr, setPhotoErr] = React.useState("");
  const [submitted, setSubmitted] = React.useState(null);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState("");
  const update = (k, v) => setData(d => ({ ...d, [k]: v }));

  const onPhotoChange = (e) => {
    setPhotoErr("");
    const f = e.target.files && e.target.files[0];
    if (!f) { setPhoto(null); return; }
    if (f.size > MAX_PHOTO_BYTES) {
      setPhotoErr(`Photo is too large (${Math.round(f.size / 1024)} KB). Max is 5 MB.`);
      e.target.value = "";
      return;
    }
    if (!/^image\/(png|jpe?g|webp|heic)$/i.test(f.type)) {
      setPhotoErr("Photo must be PNG, JPG, WEBP, or HEIC.");
      e.target.value = "";
      return;
    }
    const reader = new FileReader();
    reader.onload = () => {
      setPhoto({ dataUrl: reader.result, filename: f.name, sizeKb: Math.round(f.size / 1024) });
    };
    reader.onerror = () => setPhotoErr("Couldn't read that file. Try a different one.");
    reader.readAsDataURL(f);
  };

  const onSubmit = async (e) => {
    e.preventDefault();
    setSubmitting(true);
    setError("");
    try {
      const body = {
        type: 'testimonial',
        name: data.name,
        email: data.email,
        program: data.program,
        message: data.message,
        photo_data_url: photo?.dataUrl || null,
      };
      const res = await fetch("/api/intake", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      const json = await res.json().catch(() => ({}));
      if (!res.ok || !json.ok) throw new Error(json.error || `error_${res.status}`);
      setSubmitted({ ref: json.ref });
    } catch (err) {
      setError("Couldn't send right now. Please try again, or email Joseph.J.Pospiech@phila.gov.");
    } finally {
      setSubmitting(false);
    }
  };

  if (submitted) {
    return (
      <section className="section" style={{ background: "var(--c-cream)", minHeight: "60vh", display: "flex", alignItems: "center" }}>
        <div className="container" style={{ maxWidth: 720, textAlign: "center" }}>
          <div style={{ fontSize: 80, marginBottom: 18 }}>✦</div>
          <h2 className="display" style={{ fontSize: "clamp(40px, 7vw, 80px)", marginBottom: 18 }}>
            Thanks for sharing.
          </h2>
          <p style={{ fontSize: 18, color: "var(--c-ink-soft)", lineHeight: 1.55, maxWidth: 560, margin: "0 auto 28px" }}>
            Your testimonial is in. JJ reads every submission. We may use your story
            (with credit) on the site or in PPR program materials. Reference: {submitted.ref}.
          </p>
          <button onClick={() => { setSubmitted(null); setData(blank); setPhoto(null); }} className="btn">
            Submit another
          </button>
        </div>
      </section>
    );
  }

  return (
    <div>
      {/* Hero with single decorative photo from the Flickr album */}
      <section style={{ background: "var(--c-cream)", borderBottom: "2px solid var(--c-ink)" }}>
        <div className="container" style={{ padding: "80px 0 56px" }}>
          <div style={{ display: "grid", gridTemplateColumns: "1.1fr 0.9fr", gap: 48, alignItems: "center" }} className="testimonials-hero">
            <div>
              <div className="eyebrow">Testimonials</div>
              <h1 className="display" style={{ fontSize: "clamp(48px, 8.4vw, 124px)", margin: "12px 0 24px", lineHeight: 0.95 }}>
                Tell us<br />your<br /><span style={{ fontStyle: "italic", color: "var(--c-primary)" }}>PPR story.</span>
              </h1>
              <p style={{ fontSize: 19, lineHeight: 1.55, color: "var(--c-ink)", maxWidth: 520 }}>
                Was there a PPR Performing Arts program that meant something to you, your kid, or your community?
                We&rsquo;d love to hear it &mdash; and maybe share it (with your permission) on our site.
              </p>
              <p style={{ fontSize: 16, lineHeight: 1.6, color: "var(--c-ink-soft)", marginTop: 12, maxWidth: 520 }}>
                Photos welcome. Doesn&rsquo;t need to be polished &mdash; a phone snapshot of the kids on stage is perfect.
              </p>
            </div>
            <div style={{
              borderRadius: 22, overflow: "hidden",
              border: "2px solid var(--c-ink)", boxShadow: "var(--shadow-lift)",
              aspectRatio: "4/3",
            }}>
              <img
                src={FLICKR_HERO_PHOTO}
                alt="PPR Performing Arts performance from the City Wide Dance Festival at Venice Island"
                style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }}
              />
            </div>
          </div>
        </div>
        <style>{`
          @media (max-width: 900px) { .testimonials-hero { grid-template-columns: 1fr !important; gap: 28px !important; } }
        `}</style>
      </section>

      {/* Submission form */}
      <section className="section">
        <div className="container" style={{ maxWidth: 760 }}>
          <form onSubmit={onSubmit}>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }} className="form-row">
              <Field label="Your name" value={data.name} onChange={v => update("name", v)} required />
              <Field label="Email (optional)" type="email" value={data.email} onChange={v => update("email", v)} />
              <style>{`@media (max-width: 600px) { .form-row { grid-template-columns: 1fr !important; } }`}</style>
            </div>
            <div style={{ marginTop: 14 }}>
              <Field label="Which PPR program? (optional)" value={data.program} onChange={v => update("program", v)} />
            </div>
            <div style={{ marginTop: 14 }}>
              <Field label="Your story" type="textarea" value={data.message} onChange={v => update("message", v)} required />
            </div>

            <div style={{ marginTop: 18 }}>
              <label style={{ display: "block", fontFamily: "var(--f-mono)", fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--c-ink-soft)", marginBottom: 8 }}>
                Photo (optional, max 5 MB)
              </label>
              <input
                type="file"
                accept="image/png,image/jpeg,image/webp,image/heic"
                onChange={onPhotoChange}
                style={{ fontSize: 14 }}
              />
              {photo && (
                <div style={{ marginTop: 8, fontSize: 13, color: "var(--c-ink-soft)" }}>
                  Attached: <strong>{photo.filename}</strong> ({photo.sizeKb} KB)
                </div>
              )}
              {photoErr && (
                <div style={{ marginTop: 8, fontSize: 13, color: "var(--c-primary-deep)" }}>{photoErr}</div>
              )}
            </div>

            {error && (
              <div style={{ marginTop: 24, padding: 14, background: "#FBE4DC", border: "2px solid var(--c-primary)", borderRadius: 12, fontSize: 14, color: "var(--c-ink)" }}>
                {error}
              </div>
            )}

            <div className="card" style={{ background: "var(--c-cream-deep)", marginTop: 32, display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 14 }}>
              <div>
                <div className="display" style={{ fontSize: 20 }}>Send it.</div>
                <div style={{ fontSize: 13, color: "var(--c-ink-soft)" }}>JJ reads every one personally.</div>
              </div>
              <button type="submit" className="btn" disabled={submitting}>
                {submitting ? "Sending…" : "Submit testimonial →"}
              </button>
            </div>
          </form>
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { TestimonialsPage });
