// site-contact.jsx — Contact page with live PHP backend + newsletter.

// ── Configuration ─────────────────────────────────────────
// Path to contact.php on your server. Change if you host it elsewhere.
const CONTACT_PHP = 'contact.php';

// Expose accent colour for PHP emails
try { const d = window.loadFestivalData?.(); if (d?.festival?.accentColor) window.__festivalAccent = d.festival.accentColor; if (d?.festival?.logoImage) window.__festivalLogoImage = d.festival.logoImage; } catch(e) {}

function Contact() {
  const d   = useSite();
  const pg  = d.festival?.pages?.contact || {};

  const sidebarRows = pg.sidebarRows || [
    { id: "f",  label: "Festival", value: "LJMU MA Short Film Festival" },
    { id: "ed", label: "Edition",  value: "Sixth — March 2026" },
    { id: "h",  label: "Host",     value: "Liverpool John Moores University" },
    { id: "l",  label: "Location", value: "Liverpool, UK" },
    { id: "em", label: "Email",    value: "ljmumasff@gmail.com" },
  ];
  const social = pg.social || [
    { id: "ig", name: "Instagram", url: "https://www.instagram.com/ljmumasff/" },
    { id: "fb", name: "Facebook",  url: "https://www.facebook.com/LJMUMASFF" },
    { id: "tt", name: "TikTok",    url: "https://www.tiktok.com/@ljmumasff" },
    { id: "yt", name: "YouTube",   url: "https://www.youtube.com/@ljmumashortfilmfestival6785" },
  ];

  // ── Contact form state ──────────────────────────────────
  const [form, setForm]     = React.useState({ name: "", email: "", website: "", subject: "General enquiry", message: "" });
  const [status, setStatus] = React.useState("idle"); // idle | sending | sent | error
  const [errors, setErrors] = React.useState({});
  const [serverErr, setServerErr] = React.useState("");
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const validateForm = () => {
    const errs = {};
    if (!form.name.trim())    errs.name = true;
    if (!form.email.trim() || !/^\S+@\S+\.\S+$/.test(form.email)) errs.email = true;
    if (!form.message.trim()) errs.message = true;
    setErrors(errs);
    return !Object.keys(errs).length;
  };

  const submitContact = async (e) => {
    e.preventDefault();
    if (!validateForm()) return;
    setStatus("sending");
    setServerErr("");
    try {
      const body = new FormData();
      body.append("action",  "contact");
      body.append("accent_color", (window.__festivalAccent || "#cb5640"));
      body.append("logo_image", (window.__festivalLogoImage || ""));
      body.append("name",    form.name);
      body.append("email",   form.email);
      body.append("website", form.website);
      body.append("subject", form.subject);
      body.append("message", form.message);
      body.append("_hp",     ""); // honeypot — must stay empty

      const res  = await fetch(CONTACT_PHP, { method: "POST", body });
      const data = await res.json();
      if (data.success) {
        setStatus("sent");
        window.scrollTo({ top: 0, behavior: "smooth" });
      } else {
        setServerErr(data.error || "Something went wrong. Please try again.");
        setStatus("idle");
      }
    } catch {
      setServerErr("Could not reach the server. Please check your connection and try again.");
      setStatus("idle");
    }
  };

  const errStyle = (k) => errors[k]
    ? { borderColor: "var(--coral)", boxShadow: "0 0 0 3px rgba(203,86,64,0.15)" }
    : {};

  // ── Success screen ──────────────────────────────────────
  if (status === "sent") {
    return (
      <Page k="contact-done">
        <section className="dark section" style={{ minHeight: "60vh", display: "flex", alignItems: "center" }}>
          <div className="wrap" style={{ textAlign: "center", maxWidth: 640 }}>
            <span style={{ width: 64, height: 64, background: "var(--accent)", color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 24 }}>
              <SIcon name="check" style={{ width: 28, height: 28 }} />
            </span>
            <h1 className="display" style={{ fontSize: "clamp(36px,6vw,80px)" }}>Message sent.</h1>
            <p className="lead muted" style={{ marginTop: 20 }}>
              Thank you, {form.name}. We'll be in touch at{" "}
              <span style={{ color: "var(--paper)" }}>{form.email}</span> soon.
            </p>
            <p style={{ fontSize: 14, color: "rgba(240,238,233,0.5)", marginTop: 12 }}>
              A confirmation has been sent to your inbox.
            </p>
            <button className="btn" style={{ marginTop: 28 }}
              onClick={() => { setStatus("idle"); setForm({ name: "", email: "", website: "", subject: "General enquiry", message: "" }); }}>
              Send another message <SIcon name="arrowR" />
            </button>
          </div>
        </section>
      {/* Newsletter standalone section removed — now inside sidebar */}
    </Page>
    );
  }

  return (
    <Page k="contact">
      {/* Hero */}
      <section className="dark section tight page-hero">
        <div className="wrap">
          <span className="eyebrow">Contact</span>
          <h1 className="display" style={{ fontSize: "clamp(48px,10vw,140px)", margin: "16px 0 0" }}>
            {pg.heroTitle || "Get in touch."}
          </h1>
        </div>
      </section>

      {/* Form + sidebar */}
      <section className="section">
        <div className="wrap contact-grid" style={{ display: "grid", gridTemplateColumns: "1fr 380px", gap: 56, alignItems: "start" }}>

          {/* ── Form ── */}
          <form onSubmit={submitContact} noValidate>
            <Kicker n="§ 01">Your message</Kicker>

            {/* Name + Email */}
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
              <div className="field">
                <label className="flabel">Name *</label>
                <input className="input" value={form.name}
                  onChange={e => set("name", e.target.value)}
                  style={errStyle("name")} autoComplete="name" />
                {errors.name && <div className="label" style={{ color: "var(--coral)", marginTop: 6 }}>Please enter your name</div>}
              </div>
              <div className="field">
                <label className="flabel">Email *</label>
                <input className="input" type="email" value={form.email}
                  onChange={e => set("email", e.target.value)}
                  style={errStyle("email")} autoComplete="email" />
                {errors.email && <div className="label" style={{ color: "var(--coral)", marginTop: 6 }}>Enter a valid email</div>}
              </div>
            </div>

            {/* Website + Subject */}
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
              <div className="field">
                <label className="flabel">Website</label>
                <input className="input" type="url" value={form.website}
                  onChange={e => set("website", e.target.value)}
                  placeholder="https://" autoComplete="url" />
              </div>
              <div className="field">
                <label className="flabel">Subject</label>
                <select className="select" value={form.subject}
                  onChange={e => set("subject", e.target.value)}>
                  <option>General enquiry</option>
                  <option>Press &amp; media</option>
                  <option>Submissions</option>
                  <option>Tickets &amp; access</option>
                  <option>Partnerships &amp; sponsorship</option>
                  <option>Academic &amp; educational</option>
                  <option>Other</option>
                </select>
              </div>
            </div>

            {/* Message */}
            <div className="field">
              <label className="flabel">Message *</label>
              <textarea className="textarea" value={form.message}
                onChange={e => set("message", e.target.value)}
                rows={6} style={{ ...errStyle("message"), minHeight: 140 }} />
              {errors.message && <div className="label" style={{ color: "var(--coral)", marginTop: 6 }}>Please enter a message</div>}
            </div>

            {/* Honeypot (hidden from humans) */}
            <input name="_hp" type="text" style={{ display: "none" }} tabIndex={-1} autoComplete="off"
              onChange={() => {}} value="" />

            {/* Server error */}
            {serverErr && (
              <div style={{ background: "rgba(203,86,64,0.1)", border: "1px solid var(--coral)", padding: "12px 16px", marginBottom: 16, fontSize: 14, color: "var(--coral)" }}>
                {serverErr}
              </div>
            )}

            <button type="submit" className="btn" disabled={status === "sending"}
              style={{ marginTop: 8, padding: "16px 28px", opacity: status === "sending" ? 0.6 : 1, cursor: status === "sending" ? "wait" : "pointer" }}>
              {status === "sending" ? "Sending…" : "Send message"}
              {status !== "sending" && <SIcon name="arrowR" />}
            </button>
          </form>

          {/* ── Sidebar ── */}
          <aside style={{ position: "sticky", top: 88 }}>
            <div style={{ background: "var(--ink)", color: "var(--paper)", padding: 28 }}>
              <SidebarNewsletter />
            </div>
          </aside>

        </div>
      </section>

      {/* Newsletter standalone section removed — now inside sidebar */}
    </Page>
  );
}


// ══════════════════════════════════════════════════════════
//  SIDEBAR NEWSLETTER (compact, inside the dark sidebar box)
// ══════════════════════════════════════════════════════════
function SidebarNewsletter() {
  const [nl, setNl]         = React.useState({ name: "", email: "" });
  const [nlStatus, setNlStatus] = React.useState("idle");
  const [nlErr, setNlErr]   = React.useState("");
  const setN = (k, v) => setNl(f => ({ ...f, [k]: v }));

  const submit = async (e) => {
    e.preventDefault();
    if (!nl.email || !/^\S+@\S+\.\S+$/.test(nl.email)) { setNlErr("Enter a valid email."); return; }
    setNlStatus("sending"); setNlErr("");
    try {
      const body = new FormData();
      body.append("action", "subscribe");
      body.append("accent_color", (window.__festivalAccent || "#cb5640"));
      body.append("logo_image", (window.__festivalLogoImage || ""));
      body.append("name",   nl.name);
      body.append("email",  nl.email);
      body.append("_hp",    "");
      const res  = await fetch(CONTACT_PHP, { method: "POST", body });
      const data = await res.json();
      if (data.success) { setNlStatus("done"); }
      else { setNlErr(data.error || "Something went wrong."); setNlStatus("idle"); }
    } catch { setNlErr("Could not reach the server."); setNlStatus("idle"); }
  };

  // confirmation shown inline below the form

  return (
    <form onSubmit={submit} noValidate style={{ marginTop: 10, paddingTop: 10 }}>
      <div style={{ fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase", fontFamily: "var(--mono)", color: "var(--accent)", fontWeight: 700, marginBottom: 14, fontWeight: 700, color: "var(--accent)" }}>Stay in the loop · Join our Mailing List.</div>
      <p className="display" style={{ fontSize: "clamp(24px,3vw,32px)", color: "var(--paper)", lineHeight: 1.0, margin: "0 0 20px", letterSpacing: "-0.01em" }}>Never miss a screening.</p>
      <div className="field" style={{ marginBottom: 10 }}>
        <label className="flabel" style={{ fontSize: 10, color: "rgba(240,238,233,0.45)" }}>First name</label>
        <input className="input input-dark-ph" value={nl.name} onChange={e => setN("name", e.target.value)}
          placeholder="Optional" autoComplete="given-name"
          style={{ background: "var(--ink-2)", borderColor: "var(--line-d)", color: "var(--paper)", fontSize: 13 }} />
      </div>
      <div className="field" style={{ marginBottom: 12 }}>
        <label className="flabel" style={{ fontSize: 10, color: "rgba(240,238,233,0.45)" }}>Email *</label>
        <input className="input dark-input" type="email" value={nl.email} onChange={e => setN("email", e.target.value)}
          placeholder="your@email.com" autoComplete="email"
          style={{ background: "var(--ink-2)", borderColor: "var(--line-d)", color: "var(--paper)", fontSize: 13 }} className="input input-dark-ph" />
      </div>
      <input name="_hp" type="text" style={{ display: "none" }} tabIndex={-1} autoComplete="off" onChange={() => {}} value="" />
      {nlErr && <div style={{ fontSize: 11, color: "var(--coral)", marginBottom: 8 }}>{nlErr}</div>}
      <button type="submit" className="btn" style={{ width: "100%", justifyContent: "center", padding: "12px", opacity: nlStatus === "sending" ? 0.6 : 1 }}>
        {nlStatus === "sending" ? "Subscribing…" : "Subscribe"}
        {nlStatus !== "sending" && <SIcon name="arrowR" />}
      </button>
      <p style={{ margin: "8px 0 0", fontSize: 10, color: "rgba(240,238,233,0.3)", fontFamily: "var(--mono)", letterSpacing: "0.06em" }}>No spam. Unsubscribe anytime.</p>
      {nlStatus === "done" && (
        <div style={{ marginTop: 20, paddingTop: 16, borderTop: "1px solid var(--line-d)", display: "flex", flexDirection: "column", alignItems: "center", textAlign: "center", gap: 8 }}>
          <span style={{ width: 36, height: 36, background: "var(--accent)", color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
            <SIcon name="check" style={{ width: 16, height: 16 }} />
          </span>
          <p style={{ margin: 0, fontSize: 14, color: "var(--paper)", fontWeight: 700 }}>You're on the list!</p>
          <p style={{ margin: 0, fontSize: 11, color: "rgba(240,238,233,0.45)", fontFamily: "var(--mono)" }}>Check your inbox for confirmation. If you don't see it, check your spam folder and mark it as "Not spam".</p>
        </div>
      )}
    </form>
  );
}


// ══════════════════════════════════════════════════════════
//  NEWSLETTER SECTION (full-width, standalone)
// ══════════════════════════════════════════════════════════
function NewsletterSection() {
  const [nl, setNl]         = React.useState({ name: "", email: "" });
  const [nlStatus, setNlStatus] = React.useState("idle"); // idle | sending | done | error
  const [nlErr, setNlErr]   = React.useState("");
  const setN = (k, v) => setNl(f => ({ ...f, [k]: v }));

  const submitNewsletter = async (e) => {
    e.preventDefault();
    if (!nl.email || !/^\S+@\S+\.\S+$/.test(nl.email)) {
      setNlErr("Please enter a valid email address.");
      return;
    }
    setNlStatus("sending");
    setNlErr("");
    try {
      const body = new FormData();
      body.append("action", "subscribe");
      body.append("name",   nl.name);
      body.append("email",  nl.email);
      body.append("_hp",    "");
      const res  = await fetch(CONTACT_PHP, { method: "POST", body });
      const data = await res.json();
      if (data.success) {
        setNlStatus("done");
      } else {
        setNlErr(data.error || "Something went wrong.");
        setNlStatus("idle");
      }
    } catch {
      setNlErr("Could not reach the server.");
      setNlStatus("idle");
    }
  };

  return (
    <section className="section dark" style={{ background: "var(--ink-2)" }}>
      <div className="wrap" style={{ maxWidth: 720 }}>
        {nlStatus === "done" ? (
          <div style={{ textAlign: "center", padding: "clamp(32px,4vw,56px) 0" }}>
            <span style={{ width: 56, height: 56, background: "var(--accent)", color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 20 }}>
              <SIcon name="check" style={{ width: 24, height: 24 }} />
            </span>
            <h2 className="display" style={{ fontSize: "clamp(28px,5vw,56px)", color: "var(--paper)", margin: "0 0 12px" }}>You're on the list.</h2>
            <p style={{ fontSize: 16, color: "rgba(240,238,233,0.6)", margin: 0 }}>
              Check your inbox for a confirmation email.
            </p>
          </div>
        ) : (
          <>
            <Kicker n="§">Stay in the loop</Kicker>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "clamp(24px,4vw,48px)", alignItems: "end" }} className="newsletter-grid">
              <div>
                <h2 className="display" style={{ fontSize: "clamp(32px,5vw,64px)", color: "var(--paper)", margin: "0 0 16px", lineHeight: 1 }}>
                  Never miss a screening.
                </h2>
                <p style={{ fontSize: "clamp(14px,1.4vw,16px)", lineHeight: 1.75, color: "rgba(240,238,233,0.6)", margin: 0 }}>
                  Programme announcements, Q&amp;A sessions, award news — straight to your inbox.
                </p>
              </div>
              <form onSubmit={submitNewsletter} noValidate>
                <div className="field">
                  <label className="flabel" style={{ color: "rgba(240,238,233,0.5)" }}>First name</label>
                  <input className="input" value={nl.name}
                    onChange={e => setN("name", e.target.value)}
                    placeholder="Optional" autoComplete="given-name"
                    style={{ background: "var(--ink)", borderColor: "var(--line-d)", color: "var(--paper)" }} />
                </div>
                <div className="field">
                  <label className="flabel" style={{ color: "rgba(240,238,233,0.5)" }}>Email *</label>
                  <input className="input" type="email" value={nl.email}
                    onChange={e => setN("email", e.target.value)}
                    placeholder="your@email.com" autoComplete="email"
                    style={{ background: "var(--ink)", borderColor: "var(--line-d)", color: "var(--paper)" }} />
                </div>
                {/* Honeypot */}
                <input name="_hp" type="text" style={{ display: "none" }} tabIndex={-1} autoComplete="off" onChange={() => {}} value="" />
                {nlErr && (
                  <div style={{ fontSize: 13, color: "var(--coral)", marginBottom: 12 }}>{nlErr}</div>
                )}
                <button type="submit" className="btn"
                  disabled={nlStatus === "sending"}
                  style={{ opacity: nlStatus === "sending" ? 0.6 : 1, cursor: nlStatus === "sending" ? "wait" : "pointer" }}>
                  {nlStatus === "sending" ? "Subscribing…" : "Subscribe"}
                  {nlStatus !== "sending" && <SIcon name="arrowR" />}
                </button>
                <p style={{ marginTop: 12, fontSize: 11, color: "rgba(240,238,233,0.3)", fontFamily: "var(--mono)", letterSpacing: "0.06em" }}>
                  No spam. Unsubscribe anytime.
                </p>
              </form>
            </div>
          </>
        )}
      </div>
    </section>
  );
}

Object.assign(window, { Contact });
