/* Forms.jsx — Center submission + Workshop development forms */

function CenterSubmitPage() {
  const blank = {
    centerName: "", programName: "", programType: "", programTypeOther: "", phone: "",
    address: "", contactName: "", contactEmail: "",
    ageRange: "", schedule: "", description: "",
    programContactType: "email", programContactValue: "",
  };
  const [data, setData] = React.useState(blank);
  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 onSubmit = async (e) => {
    e.preventDefault();
    setSubmitting(true);
    setError("");
    try {
      // Map UI fields -> server fields. program_contact_phone OR program_contact_email
      // gets populated based on the chosen contact method.
      const submission = {
        ...data,
        programContactPhone: data.programContactType === "phone" ? data.programContactValue : "",
        programContactEmail: data.programContactType === "email" ? data.programContactValue : "",
      };
      const res = await fetch("/api/center-submit", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(submission)
      });
      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 <ConfirmationView
      title="Got it — thanks for submitting."
      body={`Our team reviews submissions weekly. You'll get an email when your program is approved, or if we need to adjust details before publishing. Reference: ${submitted.ref}.`}
      ctaLabel="Submit another program"
      onCta={() => { setSubmitted(null); setData(blank); }}
    />;
  }

  return (
    <div>
      <FormHero
        eyebrow="For Recreation Centers"
        title={<>Promote a program<br/>at your center.</>}
        body="Submit your program details below. Our team reviews each submission, and once approved, your program appears on the citywide map and program directory. We may reach out to adjust details before publishing."
        bg="var(--c-tertiary)"
      />
      <section className="section">
        <div className="container" style={{ maxWidth: 920 }}>
          <form onSubmit={onSubmit}>
            <FormSection number="01" title="The program">
              <Row>
                <Field label="Program name" value={data.programName} onChange={v => update("programName", v)} required />
                <Field label="Program type" type="select" options={["", "Dance", "Theater", "Music", "Acting", "Other"]} value={data.programType} onChange={v => update("programType", v)} required />
              </Row>
              {data.programType === "Other" && (
                <Field
                  label="Please specify the program type"
                  value={data.programTypeOther}
                  onChange={v => update("programTypeOther", v)}
                  required
                />
              )}
              <Row>
                <Field label="Age range" value={data.ageRange} onChange={v => update("ageRange", v)} required />
                <Field label="Schedule (day & time)" value={data.schedule} onChange={v => update("schedule", v)} required />
              </Row>
              <Field label="Short description (2–3 sentences)" type="textarea" value={data.description} onChange={v => update("description", v)} required />
            </FormSection>

            <FormSection number="02" title="The location">
              <Field label="Recreation center name" value={data.centerName} onChange={v => update("centerName", v)} required />
              <Field label="Full street address" value={data.address} onChange={v => update("address", v)} required />
              <Field label="Site phone" type="tel" value={data.phone} onChange={v => update("phone", v)} required />
            </FormSection>

            <FormSection number="03" title="Your contact info">
              <Row>
                <Field label="Your name" value={data.contactName} onChange={v => update("contactName", v)} required />
                <Field label="Your email" type="email" value={data.contactEmail} onChange={v => update("contactEmail", v)} required />
              </Row>
            </FormSection>

            <FormSection number="04" title="How should the public reach this program?">
              <p style={{ fontSize: 13.5, color: "var(--c-ink-soft)", marginTop: -4, lineHeight: 1.55 }}>
                We&apos;ll publish this on the public Programs map so families can ask
                questions and sign up. Use whichever method you check most.
              </p>
              <Row>
                <Field
                  label="Best contact method"
                  type="select"
                  options={["email", "phone"]}
                  optionLabels={["Email", "Phone"]}
                  value={data.programContactType}
                  onChange={v => update("programContactType", v)}
                  required
                />
                <Field
                  label={data.programContactType === "phone" ? "Public phone number" : "Public email address"}
                  type={data.programContactType === "phone" ? "tel" : "email"}
                  value={data.programContactValue}
                  onChange={v => update("programContactValue", v)}
                  required
                />
              </Row>
            </FormSection>

            {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 }}>Ready to submit?</div>
                <div style={{ fontSize: 13, color: "var(--c-ink-soft)" }}>We'll review and reply within 5 business days.</div>
              </div>
              <button type="submit" className="btn" disabled={submitting}>
                {submitting ? "Sending…" : "Submit for review →"}
              </button>
            </div>
          </form>
        </div>
      </section>
    </div>
  );
}

function WorkshopPage() {
  const blank = {
    name: "", email: "", phone: "", skill: "", experience: "",
    audience: "", availability: "", website: "",
  };
  const [data, setData] = React.useState(blank);
  const [submitted, setSubmitted] = React.useState(null);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState("");
  const update = (k, v) => setData({ ...data, [k]: v });

  const onSubmit = async (e) => {
    e.preventDefault();
    setSubmitting(true);
    setError("");
    try {
      const res = await fetch("/api/workshop", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data)
      });
      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 <ConfirmationView
      title="Thanks — we'll be in touch."
      body={`JJ will reach out within two weeks to talk about workshop programming and potential scheduling. Reference: ${submitted.ref}.`}
      ctaLabel="Submit another"
      onCta={() => { setSubmitted(null); setData(blank); }}
    />;
  }

  return (
    <div>
      <FormHero
        eyebrow="Workshop Development"
        title={<>Lead a workshop<br/>with PPR.</>}
        body="Got a skill you'd love to share — improv, sound design, lighting, hip-hop choreography, costuming, songwriting, anything? Tell us about you and what you'd teach. We schedule workshops year-round at rec centers across the city."
        bg="var(--c-accent)"
      />
      <section className="section">
        <div className="container" style={{ maxWidth: 880 }}>
          <form onSubmit={onSubmit}>
            <FormSection number="01" title="Tell us about you">
              <Row>
                <Field label="Your name" value={data.name} onChange={v => update("name", v)} required />
                <Field label="Email" type="email" value={data.email} onChange={v => update("email", v)} required />
              </Row>
              <Row>
                <Field label="Phone (optional)" type="tel" value={data.phone} onChange={v => update("phone", v)} />
                <Field label="Website / portfolio / IG (optional)" value={data.website} onChange={v => update("website", v)} />
              </Row>
            </FormSection>

            <FormSection number="02" title="What would you teach?">
              <Field label="Skill or workshop topic" value={data.skill} onChange={v => update("skill", v)} required />
              <Field label="Brief: your experience with this skill" type="textarea" value={data.experience} onChange={v => update("experience", v)} required />
              <Row>
                <Field label="Best fit for which age group?" type="select" options={["", "Ages 6–11", "Ages 12–18", "Adults", "Mixed", "Any"]} value={data.audience} onChange={v => update("audience", v)} required />
                <Field label="When are you generally available?" value={data.availability} onChange={v => update("availability", v)} />
              </Row>
            </FormSection>

            {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 }}>Sound good?</div>
                <div style={{ fontSize: 13, color: "var(--c-ink-soft)" }}>We'll reach out within two weeks.</div>
              </div>
              <button type="submit" className="btn" disabled={submitting}>
                {submitting ? "Sending…" : "Send to PPR →"}
              </button>
            </div>
          </form>
        </div>
      </section>
    </div>
  );
}

function FormHero({ eyebrow, title, body, bg }) {
  return (
    <section style={{ background: bg, color: "var(--c-ink)", padding: "80px 0 64px", borderBottom: "2px solid var(--c-ink)" }}>
      <div className="container">
        <div className="eyebrow">{eyebrow}</div>
        <h1 className="display" style={{ fontSize: "clamp(44px, 7.5vw, 96px)", margin: "12px 0 18px", lineHeight: 0.98 }}>
          {title}
        </h1>
        <p style={{ fontSize: 17, maxWidth: 700, lineHeight: 1.55 }}>{body}</p>
      </div>
    </section>
  );
}

function FormSection({ number, title, children }) {
  return (
    <div style={{ borderTop: "2px solid var(--c-ink)", paddingTop: 32, marginTop: 32 }}>
      <div style={{ display: "flex", alignItems: "baseline", gap: 14, marginBottom: 22 }}>
        <span className="display" style={{ fontSize: 32, color: "var(--c-primary)" }}>{number}</span>
        <span className="display" style={{ fontSize: 28 }}>{title}</span>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>{children}</div>
    </div>
  );
}

function Row({ children }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }} className="form-row">
      {children}
      <style>{`@media (max-width: 600px) { .form-row { grid-template-columns: 1fr !important; } }`}</style>
    </div>
  );
}

function ConfirmationView({ title, body, ctaLabel, onCta, secondary }) {
  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 }}>{title}</h2>
        <p style={{ fontSize: 18, color: "var(--c-ink-soft)", lineHeight: 1.55, maxWidth: 560, margin: "0 auto 28px" }}>{body}</p>
        <div style={{ display: "inline-flex", gap: 12, flexWrap: "wrap", justifyContent: "center" }}>
          {secondary && <button onClick={secondary.onClick} className="btn secondary">{secondary.label}</button>}
          <button onClick={onCta} className="btn">{ctaLabel}</button>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { CenterSubmitPage, WorkshopPage, FormHero, FormSection, Row, ConfirmationView });
