/* ART ADDA — Submission form (multi-step, validated) */
function Submit({ go }) {
  useReveal();
  const D = window.ARTADDA;
  const STEPS = ["You", "Your Practice", "Your Work"];
  const [step, setStep] = useState(0);
  const [done, setDone] = useState(false);
  const [data, setData] = useState({
    name: "", phone: "", email: "", community: "",
    discipline: "", bio: "", mediums: [], instagram: "", website: "",
    files: [],
  });
  const [errors, setErrors] = useState({});
  const dropRef = useRef(null);
  const [dragging, setDragging] = useState(false);

  const set = (k, v) => setData((d) => ({ ...d, [k]: v }));
  const toggleMedium = (m) =>
    setData((d) => ({ ...d, mediums: d.mediums.includes(m) ? d.mediums.filter((x) => x !== m) : [...d.mediums, m] }));

  const MEDIUMS = ["Oil", "Acrylic", "Watercolour", "Charcoal", "Pencil", "Pastel", "Mural", "Mosaic", "Photography", "Illustration", "Digital", "Mixed Media"];

  function validate(s) {
    const e = {};
    if (s === 0) {
      if (!data.name.trim()) e.name = "Required";
      if (!data.phone.trim()) e.phone = "Required";
      else if (!/^[+0-9 ()-]{7,}$/.test(data.phone.trim())) e.phone = "Enter a valid phone number";
      if (data.email && !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(data.email.trim())) e.email = "Enter a valid email";
    }
    if (s === 1) {
      if (!data.discipline.trim()) e.discipline = "Required";
      if (!data.bio.trim()) e.bio = "Tell us a little about your practice";
      else if (data.bio.trim().length < 30) e.bio = "A little more — at least a sentence or two";
      if (data.mediums.length === 0) e.mediums = "Pick at least one";
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  }

  function next() { if (validate(step)) setStep((s) => Math.min(s + 1, STEPS.length - 1)); }
  function prev() { setStep((s) => Math.max(s - 1, 0)); }
  function submit() { if (validate(step)) { setDone(true); window.scrollTo({ top: 0, behavior: "smooth" }); } }

  function addFiles(fileList) {
    const arr = Array.from(fileList).filter((f) => f.type.startsWith("image/")).slice(0, 8);
    const readers = arr.map(
      (f) => new Promise((res) => {
        const r = new FileReader();
        r.onload = () => res({ name: f.name, url: r.result });
        r.readAsDataURL(f);
      })
    );
    Promise.all(readers).then((imgs) => set("files", [...data.files, ...imgs].slice(0, 8)));
  }

  if (done) {
    return (
      <div className="rise-in wrap section">
        <div className="success">
          <div className="success__mark serif">✓</div>
          <p className="eyebrow" style={{ marginBottom: 18 }}>Submission received</p>
          <h1 className="h-lg serif" style={{ maxWidth: "16ch", margin: "0 auto 22px" }}>Thank you, {data.name.split(" ")[0]}.</h1>
          <p className="lede" style={{ maxWidth: "46ch", margin: "0 auto 12px" }}>
            We've got your details and {data.files.length || "your"} sample{data.files.length === 1 ? "" : "s"}. {D.contact.lead} curate each edition and will be in touch about an upcoming Sunday.
          </p>
          <p className="muted" style={{ marginBottom: 34 }}>In the meantime, have a read of the participating-artist guidelines.</p>
          <div style={{ display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap" }}>
            <button className="btn" onClick={() => go("guidelines")}>Read the guidelines <Arrow /></button>
            <button className="btn btn--ghost" onClick={() => { setDone(false); setStep(0); setData({ name: "", phone: "", email: "", community: "", discipline: "", bio: "", mediums: [], instagram: "", website: "", files: [] }); }}>Submit another</button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="rise-in">
      <section className="wrap page-intro">
        <p className="eyebrow reveal" style={{ marginBottom: 22 }}>Participate</p>
        <h1 className="serif reveal">Show your<br />work</h1>
        <p className="lede reveal" style={{ maxWidth: "52ch", marginTop: 26 }}>
          Art Adda runs monthly. Tell us about yourself and your work — {D.contact.lead} curate each edition and will reach out about a Sunday that fits.
        </p>
      </section>

      <section className="wrap section" style={{ paddingTop: "clamp(30px,4vw,50px)" }}>
        <div className="form-wrap">
          <aside className="form-aside">
            <div className="step-track">
              {STEPS.map((_, i) => (
                <div key={i} className={"step-track__dot" + (i < step ? " done" : i === step ? " active" : "")} />
              ))}
            </div>
            <p className="step-label">Step {step + 1} / {STEPS.length}</p>
            <h2 className="h-md serif" style={{ marginBottom: 16 }}>{STEPS[step]}</h2>
            <p className="muted" style={{ fontSize: 15 }}>
              {step === 0 && "How we reach you. Your phone number is how we coordinate the day."}
              {step === 1 && "Your medium and a short bio — this is what we share with the community."}
              {step === 2 && "A few sample images so we can get a feel for your work. Optional, but lovely to have."}
            </p>
          </aside>

          <div>
            {step === 0 && (
              <div>
                <Field label="Full name" req error={errors.name}>
                  <input value={data.name} onChange={(e) => set("name", e.target.value)} placeholder="e.g. Priya Hegde" />
                </Field>
                <Field label="Contact number" req error={errors.phone}>
                  <input value={data.phone} onChange={(e) => set("phone", e.target.value)} placeholder="98xxxxxxxx" inputMode="tel" />
                </Field>
                <Field label="Email" error={errors.email} hint="Optional">
                  <input value={data.email} onChange={(e) => set("email", e.target.value)} placeholder="you@email.com" inputMode="email" />
                </Field>
                <Field label="Malhar community" hint="Optional — e.g. Malhar Medley, Mosaic, Patterns">
                  <input value={data.community} onChange={(e) => set("community", e.target.value)} placeholder="Which community block?" />
                </Field>
              </div>
            )}

            {step === 1 && (
              <div>
                <Field label="Discipline / what you make" req error={errors.discipline}>
                  <input value={data.discipline} onChange={(e) => set("discipline", e.target.value)} placeholder="e.g. Watercolour · Urban Sketching" />
                </Field>
                <Field label="Mediums you work in" req error={errors.mediums}>
                  <div className="medium-pick">
                    {MEDIUMS.map((m) => (
                      <button type="button" key={m} className={data.mediums.includes(m) ? "on" : ""} onClick={() => toggleMedium(m)}>{m}</button>
                    ))}
                  </div>
                </Field>
                <Field label="A short bio / artist statement" req error={errors.bio} hint={`${data.bio.trim().length} characters`}>
                  <textarea value={data.bio} onChange={(e) => set("bio", e.target.value)} rows={5} placeholder="What draws you to your work? How did you start? What will you show?" />
                </Field>
                <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 24 }}>
                  <Field label="Instagram" hint="Optional">
                    <input value={data.instagram} onChange={(e) => set("instagram", e.target.value)} placeholder="@handle" />
                  </Field>
                  <Field label="Website" hint="Optional">
                    <input value={data.website} onChange={(e) => set("website", e.target.value)} placeholder="yoursite.com" />
                  </Field>
                </div>
              </div>
            )}

            {step === 2 && (
              <div>
                <Field label="Sample artwork" hint="Up to 8 images · JPG or PNG">
                  <div
                    ref={dropRef}
                    className={"dropzone" + (dragging ? " drag" : "")}
                    onClick={() => dropRef.current.querySelector("input").click()}
                    onDragOver={(e) => { e.preventDefault(); setDragging(true); }}
                    onDragLeave={() => setDragging(false)}
                    onDrop={(e) => { e.preventDefault(); setDragging(false); addFiles(e.dataTransfer.files); }}
                  >
                    <p className="mono">Drop images here, or click to browse</p>
                    <input type="file" accept="image/*" multiple style={{ display: "none" }} onChange={(e) => addFiles(e.target.files)} />
                  </div>
                  {data.files.length > 0 && (
                    <div className="thumbs">
                      {data.files.map((f, i) => (
                        <div className="thumb" key={i}>
                          <img src={f.url} alt={f.name} />
                          <button type="button" onClick={() => set("files", data.files.filter((_, k) => k !== i))}>✕</button>
                        </div>
                      ))}
                    </div>
                  )}
                </Field>
                <div style={{ background: "var(--paper-2)", padding: 24, marginTop: 12 }}>
                  <p className="mono" style={{ fontSize: 11, letterSpacing: ".12em", textTransform: "uppercase", color: "var(--ink-faint)", marginBottom: 14 }}>Review</p>
                  <div className="flow" style={{ fontSize: 15 }}>
                    <div><strong className="serif" style={{ fontSize: 18 }}>{data.name || "—"}</strong> <span className="muted">· {data.phone || "no phone"}</span></div>
                    <div className="muted">{data.discipline || "—"} · {data.mediums.join(", ") || "no mediums"}</div>
                  </div>
                </div>
              </div>
            )}

            <div className="form-actions">
              {step > 0 ? <button className="btn btn--ghost" onClick={prev}>Back</button> : <span className="faint mono" style={{ fontSize: 12 }}>Curated by {D.contact.lead}</span>}
              {step < STEPS.length - 1
                ? <button className="btn" onClick={next}>Continue <Arrow /></button>
                : <button className="btn" onClick={submit}>Submit <Arrow /></button>}
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}

function Field({ label, req, error, hint, children }) {
  return (
    <div className={"field" + (error ? " err" : "")}>
      <label>{label} {req && <span className="req">*</span>}</label>
      {children}
      {error ? <div className="field__err">{error}</div> : hint ? <div className="field__hint">{hint}</div> : null}
    </div>
  );
}
window.Submit = Submit;
