// Page: Classes — types (from settings), Heather bio, booking form
const { useState: useStateClasses } = React;

function ClassesPage({ pushToast, classes }) {
  const list = (Array.isArray(classes) && classes.length) ? classes : DEFAULT_CLASSES;
  const firstId = list[0]?.id || "";

  const [form, setForm] = useStateClasses({
    name: "", email: "", phone: "",
    classType: firstId,
    date1: "", date2: "",
    times: [],
    other: "",
    notes: "",
  });
  const [errors, setErrors] = useStateClasses({});
  const [sent, setSent] = useStateClasses(false);
  const [sending, setSending] = useStateClasses(false);

  React.useEffect(() => {
    // If settings load after first render, point at the first available class.
    if (!form.classType && firstId) setForm((f) => ({ ...f, classType: firstId }));
  }, [firstId]);

  function update(k, v) { setForm((f) => ({ ...f, [k]: v })); }
  function toggleTime(t) {
    setForm((f) => ({
      ...f,
      times: f.times.includes(t) ? f.times.filter((x) => x !== t) : [...f.times, t],
    }));
  }

  function validate() {
    const e = {};
    if (!form.name.trim()) e.name = "Please tell us your name.";
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = "Enter a valid email.";
    if (!form.phone.trim()) e.phone = "Phone helps us confirm quickly.";
    if (!form.date1) e.date1 = "Please pick at least one preferred date.";
    if (form.times.length === 0 && !form.other.trim()) e.times = "Pick a time of day, or tell us another time that works.";
    setErrors(e);
    return Object.keys(e).length === 0;
  }

  async function submit(ev) {
    ev.preventDefault();
    if (!validate()) return;
    setSending(true);
    try {
      const res = await fetch("/booking", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });
      if (!res.ok) throw new Error("send failed");
      setSent(true);
      pushToast && pushToast("Booking request sent! Heather will be in touch soon.");
      setForm({
        name: "", email: "", phone: "", classType: firstId,
        date1: "", date2: "", times: [], other: "", notes: "",
      });
      setTimeout(() => setSent(false), 4000);
    } catch (err) {
      console.error("[class booking]", err);
      pushToast && pushToast("Sorry — something went wrong. Please try again.");
    } finally {
      setSending(false);
    }
  }

  return (
    <main id="main">
      <PageHeader
        eyebrow="Learn to sew"
        title="Classes with Heather"
        sub="Patient, project-based teaching at a quiet pace. Most students go from never-touched-a-machine to finishing their first make in a single afternoon."
      />

      <section className="section" style={{ paddingTop: 32 }}>
        <div className="container">
          <h2 style={{ marginBottom: 24 }}>Class types</h2>
          <div className="tiles">
            {list.map((l) => (
              <div key={l.id} className="tile" style={{ cursor: "default" }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                  <h3>{l.name}</h3>
                  <span style={{ fontFamily: "var(--font-serif)", color: "var(--accent)", fontSize: "1.15rem" }}>£{Number(l.price).toFixed(0)}</span>
                </div>
                <span className="tag">{l.duration}</span>
                <p>{l.desc}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Heather bio */}
      <section className="section" style={{ background: "var(--bg-2)", paddingTop: 56 }}>
        <div className="container">
          <div className="two-col" style={{ alignItems: "center" }}>
            <div className="stitch-frame" style={{ aspectRatio: "4/5", background: "var(--bg)", borderRadius: 16, overflow: "hidden", maxWidth: 420 }}>
              <img src="images/quilt-batik.jpg" alt="Heather's batik patchwork quilt" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
            </div>
            <div>
              <div className="eyebrow">Your teacher</div>
              <h2 style={{ marginTop: 12 }}>Hi, I'm Heather.</h2>
              <p style={{ color: "var(--ink-2)", fontSize: "1.05rem" }}>
                I've been sewing for as long as I can remember and teaching for over a decade. The studio is calm,
                quiet, and welcoming — there's tea on the go, no pressure, and absolutely no silly questions. We work
                at your pace on something you'll actually take home and use.
              </p>
              <ul style={{ paddingLeft: 18, color: "var(--ink-2)", lineHeight: 1.9 }}>
                <li>One-to-one or small groups (max 3)</li>
                <li>All materials and machines provided</li>
                <li>Bring your own machine if you'd like to learn it</li>
                <li>Beginners genuinely welcome</li>
              </ul>
            </div>
          </div>
        </div>
      </section>

      {/* Process */}
      <section className="section">
        <div className="container">
          <h2 style={{ marginBottom: 16 }}>How a class works</h2>
          <div className="process">
            {[
              ["01", "Send a request", "Use the form below — tell me what you'd like to learn and when."],
              ["02", "We confirm", "I'll reply within 1–2 working days with a time and what to bring."],
              ["03", "Come in", "Tea, fabric, machines, patience. We work at your pace."],
              ["04", "Take it home", "Leave with a finished make and the skills to do it again."],
            ].map(([n, t, d]) => (
              <div key={n} className="step">
                <div className="num">{n}</div>
                <h4>{t}</h4>
                <p style={{ color: "var(--ink-2)", margin: 0, fontSize: ".95rem" }}>{d}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Booking form */}
      <section className="section" style={{ paddingTop: 0 }}>
        <div className="container">
          <div className="stitch-frame" style={{ background: "var(--surface)", borderRadius: 16, border: "1px solid var(--line)", padding: 32 }}>
            <h2 style={{ marginBottom: 8 }}>Request a class</h2>
            <p style={{ color: "var(--ink-2)", marginBottom: 24 }}>
              Fill this in and Heather will be in touch to confirm.
            </p>

            <form onSubmit={submit} noValidate style={{ display: "grid", gap: 16, gridTemplateColumns: "1fr" }}>
              <div style={{ display: "grid", gap: 16, gridTemplateColumns: "1fr 1fr" }}>
                <div className="field">
                  <label htmlFor="bk-name">Name *</label>
                  <input id="bk-name" className="input" value={form.name} onChange={(e) => update("name", e.target.value)} />
                  {errors.name && <span className="error-text">{errors.name}</span>}
                </div>
                <div className="field">
                  <label htmlFor="bk-phone">Phone *</label>
                  <input id="bk-phone" className="input" value={form.phone} onChange={(e) => update("phone", e.target.value)} />
                  {errors.phone && <span className="error-text">{errors.phone}</span>}
                </div>
              </div>
              <div className="field">
                <label htmlFor="bk-email">Email *</label>
                <input id="bk-email" className="input" type="email" value={form.email} onChange={(e) => update("email", e.target.value)} />
                {errors.email && <span className="error-text">{errors.email}</span>}
              </div>

              <div className="field">
                <label htmlFor="bk-type">Class type *</label>
                <select id="bk-type" className="select" value={form.classType}
                        onChange={(e) => update("classType", e.target.value)}>
                  {list.map((l) => (
                    <option key={l.id} value={l.id}>{l.name} — {l.duration} · £{Number(l.price).toFixed(0)}</option>
                  ))}
                </select>
              </div>

              <div style={{ display: "grid", gap: 16, gridTemplateColumns: "1fr 1fr" }}>
                <div className="field">
                  <label htmlFor="bk-d1">Preferred date *</label>
                  <input id="bk-d1" className="input" type="date" value={form.date1} onChange={(e) => update("date1", e.target.value)} />
                  {errors.date1 && <span className="error-text">{errors.date1}</span>}
                </div>
                <div className="field">
                  <label htmlFor="bk-d2">Backup date</label>
                  <input id="bk-d2" className="input" type="date" value={form.date2} onChange={(e) => update("date2", e.target.value)} />
                </div>
              </div>

              <div className="field">
                <label>Preferred time of day</label>
                <div style={{ display: "flex", gap: 16, flexWrap: "wrap" }}>
                  {["Morning", "Afternoon", "Evening"].map((t) => (
                    <label key={t} className="checkbox-row">
                      <input type="checkbox" checked={form.times.includes(t)} onChange={() => toggleTime(t)} />
                      <span>{t}</span>
                    </label>
                  ))}
                </div>
                {errors.times && <span className="error-text">{errors.times}</span>}
              </div>

              <div className="field">
                <label htmlFor="bk-other">Other times you're available</label>
                <input id="bk-other" className="input" placeholder="e.g. Saturday afternoons, Tuesday after 6pm…"
                       value={form.other} onChange={(e) => update("other", e.target.value)} />
              </div>

              <div className="field">
                <label htmlFor="bk-notes">Notes</label>
                <textarea id="bk-notes" className="textarea"
                          placeholder="Any goals, projects, or experience to share?"
                          value={form.notes} onChange={(e) => update("notes", e.target.value)} />
              </div>

              <button className="btn btn-primary" type="submit" disabled={sending}
                      style={{ justifySelf: "start", opacity: sending ? 0.6 : 1 }}>
                {sending ? "Sending…" : <React.Fragment>Send booking request <Icon.Arrow /></React.Fragment>}
              </button>
              {sent && <div style={{ color: "var(--accent)", fontWeight: 700 }}>Sent! We'll be in touch.</div>}
            </form>
          </div>
        </div>
      </section>
    </main>
  );
}

Object.assign(window, { ClassesPage });
