// REWIND website — PRIVATE EVENT. Image-led hero, the space, our three rooms,
// getting here (map), FAQ, and a basic-info inquiry form. White type, champagne
// buttons, framed photography — same restrained vocabulary as the rest of site.
// Native <select> popups are drawn by the OS and cannot be styled, so the two
// pickers use a listbox in the site's own language. The hidden input keeps the
// FormData payload identical.
function RWSelect({ id, name, options, placeholder }) {
  const [open, setOpen] = React.useState(false);
  const [val, setVal] = React.useState("");
  const [active, setActive] = React.useState(0);
  const wrap = React.useRef(null);

  React.useEffect(() => {
    if (!open) return;
    const away = (e) => { if (wrap.current && !wrap.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", away);
    return () => document.removeEventListener("mousedown", away);
  }, [open]);

  const choose = (o) => { setVal(o); setOpen(false); };
  const key = (e) => {
    if (e.key === "Escape") { setOpen(false); return; }
    if (e.key === "Enter" || e.key === " ") {
      e.preventDefault();
      if (open) choose(options[active]); else { setOpen(true); setActive(Math.max(0, options.indexOf(val))); }
      return;
    }
    if (e.key === "ArrowDown" || e.key === "ArrowUp") {
      e.preventDefault();
      if (!open) { setOpen(true); return; }
      setActive((a) => (a + (e.key === "ArrowDown" ? 1 : options.length - 1)) % options.length);
    }
  };

  return (
    <div className="rwsel" ref={wrap}>
      <input type="hidden" name={name} value={val} />
      <div id={id} className="rwsel-trigger" role="combobox" tabIndex={0}
        aria-expanded={open} aria-haspopup="listbox" aria-controls={id + "-list"}
        onClick={() => setOpen((o) => !o)} onKeyDown={key}>
        <span className={val ? "rwsel-val" : "rwsel-ph"}>{val || placeholder}</span>
        <span className="rwsel-caret" aria-hidden="true"></span>
      </div>
      {open &&
        <ul className="rwsel-list" id={id + "-list"} role="listbox">
          {options.map((o, i) => (
            <li key={o} role="option" aria-selected={o === val}
              className={"rwsel-opt" + (i === active ? " is-active" : "") + (o === val ? " is-sel" : "")}
              onMouseEnter={() => setActive(i)} onClick={() => choose(o)}>{o}</li>
          ))}
        </ul>}
    </div>
  );
}

function PrivateEventView() {
  const U = window.RW_CONTENT.ui.privateEvents;
  const M = window.RW_CONTENT.media || {};
  const media = (value, fallback) => value ? (/^(data:|https?:|\/)/.test(value) ? value : RWA(value)) : fallback;
  const spaces = U.spaces.map((space, index) => ({ ...space, img: index === 0 ? (M.privateLoungeImage || window.RW_IMG.spaceLounge) : media(M.privateEventRoomImage, RWA("c-vip-event-space-1920w")) }));
  const faqs = U.faqs;
  const withEmail = (text) => text.replace("{email}", window.RW_DATA.contact.events);

  const [openFaq, setOpenFaq] = React.useState(0);
  const [sent, setSent] = React.useState(false);
  const sentRef = React.useRef(null);
  // The confirmation replaces the form, so focus has to follow it — otherwise a
  // keyboard or screen-reader user is left on a control that no longer exists.
  React.useEffect(() => { if (sent && sentRef.current) sentRef.current.focus(); }, [sent]);
  // Times are picked in half-hour steps; the end time may not precede the start.
  const [startT, setStartT] = React.useState("");
  const [endT, setEndT] = React.useState("");
  const timeErr = startT && endT && endT <= startT;
  // No point offering a date in the past, and the picker should open on a tap
  // anywhere in the field — not only on the small indicator glyph.
  const todayISO = new Date().toISOString().slice(0, 10);
  const openPicker = (e) => {
    const el = e.currentTarget;
    if (el.showPicker) {try {el.showPicker();} catch (_) {}}
  };

  // The inquiry goes to a Google Sheet via an Apps Script Web App. `no-cors` +
  // text/plain keeps it a simple request (no preflight), which means the reply
  // is opaque — so a copy is kept in localStorage and the confirmation always
  // shows the events address as a fallback route.
  const submit = (e) => {
    e.preventDefault();
    if (timeErr) return;
    const f = new FormData(e.currentTarget);
    const payload = {
      form: "private-event",
      name: f.get("name") || "",
      email: f.get("email") || "",
      phone: f.get("tel") || "",
      partySize: f.get("partySize") || "",
      space: f.get("space") || "",
      date: f.get("date") || "",
      start: f.get("start") || "",
      end: f.get("end") || "",
      eventType: f.get("eventType") || "",
      notes: f.get("notes") || "",
      capturedAt: new Date().toISOString() };
    try { localStorage.setItem("rw-private-inquiry", JSON.stringify(payload)); } catch (_) {}
    const url = window.RW_DATA.formEndpoint;
    if (url) {
      try {
        fetch(url, { method: "POST", mode: "no-cors",
          headers: { "Content-Type": "text/plain;charset=utf-8" },
          body: JSON.stringify(payload) }).catch(() => {});
      } catch (_) {}
    }
    setSent(true);
  };

  return (
    <div>
      {/* image-led hero */}
      <section className="phero">
        <img className="pimg" src={M.privateHeroImage || window.RW_IMG.gkBooth} alt="" style={{ opacity: 0.8 }} />
        <div className="pscrim"></div>
        <div className="plabel">
          <div className="cta-row" style={{ marginTop: "var(--vs-3)", justifyContent: "center" }}>
            <a className="btn btn--champ btn--lg" href="#enquire">{U.book}</a>
          </div>
        </div>
      </section>

      {/* our space */}
      <section className="sec">
        <div className="wrap">
          <div className="spaces">
            {spaces.map((s) =>
            <div key={s.name} className="spacecard">
                <div className="top"><img src={s.img} alt={s.name} /></div>
                <div className="body">
                  <h3 className="rw-subtitle" style={{ margin: 0 }}>{s.name}</h3>
                  <span className="eyebrow" style={{ color: "var(--ink)" }}>{s.capacity}</span>
                  <p className="lead" style={{ margin: "4px 0 0" }}>{s.description}</p>
                  <ul style={{ listStyle: "none", margin: "8px 0 0", padding: 0 }}>
                    {s.points.map((p) =>
                  <li key={p.value} className="rw-body-sm" style={{ position: "relative", paddingLeft: 16, marginBottom: 10, lineHeight: 1.5, color: "var(--ink)" }}>
                        <span style={{ position: "absolute", left: 0, top: 0, color: "var(--ink-faint)" }}>·</span>{p.value}
                      </li>
                  )}
                  </ul>
                </div>
              </div>
            )}
          </div>
        </div>
      </section>

      {/* FAQ */}
      <section className="sec">
        <div className="wrap">
          <div className="sec-head" style={{ marginBottom: "var(--vs-5)" }}>
            <h2 className="rw-marquee title" style={{ margin: 0 }}>{U.faqHeading}</h2>
          </div>
          <div style={{ maxWidth: 760, margin: "0 auto" }}>
            {faqs.map(({ question: q, answer: a }, i) => {
              const open = openFaq === i;
              return (
                <div key={i}>
                  <button type="button" className="faq-q" id={"pe-q-" + i}
                  aria-expanded={open} aria-controls={"pe-a-" + i}
                  onClick={() => setOpenFaq(open ? -1 : i)}>
                    <span className="rw-subtitle" style={{ fontWeight: "var(--wt-light)" }}>{q}</span>
                    <span aria-hidden="true" style={{ fontSize: 20, lineHeight: 1, flex: "0 0 auto", color: "var(--ink-muted)" }}>{open ? "–" : "+"}</span>
                  </button>
                  {open && <p className="faq-a rw-body" id={"pe-a-" + i}>{a}</p>}
                </div>);

            })}
          </div>
        </div>
      </section>

      {/* enquire */}
      <section className="sec" id="enquire">
        <div className="wrap">
          <div className="sec-head" style={{ marginBottom: "var(--vs-5)" }}>
            <span className="eyebrow">{U.inquire}</span>
            <h2 className="rw-marquee title" style={{ margin: 0 }}>{U.details}</h2>
            <p className="lead" style={{ textAlign: "center", margin: "0 auto" }}>{U.lead}</p>
          </div>
          <div style={{ maxWidth: 720, margin: "0 auto" }}>
            {sent ?
            <div ref={sentRef} data-rw-field="privateEventsContact" tabIndex={-1} role="status" style={{ border: "var(--bw) solid var(--hairline)", background: "var(--surface)", padding: "var(--sp-4)", display: "flex", flexDirection: "column", gap: "12px", alignItems: "flex-start" }}>
                <span className="eyebrow" style={{ color: "var(--ink)" }}>{U.received}</span>
                <p className="rw-subtitle" style={{ margin: 0 }}>{U.thanks}</p>
                <p className="lead" style={{ margin: 0 }}>{withEmail(U.direct)}</p>
                <button type="button" className="btn btn--secondary btn--sm" onClick={() => setSent(false)}>{U.edit}</button>
              </div> :

            <form data-rw-field="privateEventsFormEndpoint" onSubmit={submit}>
                {/* clicking anywhere in a date / time field opens the native
                    calendar or clock, not just the small indicator */}
                <div className="fgrid">
                  <div className="field"><label htmlFor="pe-name">Name</label><input id="pe-name" name="name" autoComplete="name" placeholder="Your name" required /></div>
                  <div className="field"><label htmlFor="pe-email">Email</label><input id="pe-email" name="email" type="email" autoComplete="email" placeholder="you@email.com" required /></div>
                  <div className="field"><label htmlFor="pe-phone">Phone</label><input id="pe-phone" name="tel" type="tel" autoComplete="tel" placeholder="(212) 555 0134" required /></div>
                  <div className="field"><label htmlFor="pe-size">Party size</label><input id="pe-size" name="partySize" type="text" inputMode="numeric" pattern="[0-9]*" placeholder="Number of guests" required /></div>
                  <div className="field"><label htmlFor="pe-space">Space</label>
                    <RWSelect id="pe-space" name="space" placeholder="Select one"
                      options={["Lounge", "Event Room"]} />
                  </div>
                  <div className="field"><label htmlFor="pe-date">Event date</label>
                    <input id="pe-date" name="date" type="date" min={todayISO} onClick={openPicker} onFocus={openPicker} />
                  </div>
                  <div className="field"><label htmlFor="pe-start">Start time</label>
                    <input id="pe-start" name="start" type="time" step="1800" value={startT} onClick={openPicker} onFocus={openPicker} onChange={(e) => setStartT(e.target.value)} />
                  </div>
                  <div className="field"><label htmlFor="pe-end">End time</label>
                    <input id="pe-end" name="end" type="time" step="1800" value={endT} min={startT || undefined}
                    aria-invalid={timeErr ? "true" : undefined} aria-describedby={timeErr ? "pe-end-err" : undefined}
                    onClick={openPicker} onFocus={openPicker} onChange={(e) => setEndT(e.target.value)} />
                    {timeErr && <span className="field-err" id="pe-end-err" role="alert">End time must be after the start time.</span>}
                  </div>
                  <div className="field"><label htmlFor="pe-type">Event type</label>
                    <RWSelect id="pe-type" name="eventType" placeholder="Select one"
                      options={["Corporate party", "Birthday / anniversary",
                        "Wedding / engagement party / baby shower", "Fundraiser / product launch",
                        "Photo / film shoot", "Sporting event", "Movie night", "Other"]} />
                  </div>
                  <div className="field ffull"><label htmlFor="pe-notes">Notes</label><textarea id="pe-notes" name="notes" rows={3} placeholder="Anything else we should know?"></textarea></div>
                </div>
                <div style={{ marginTop: "var(--vs-4)" }}>
                  <button className="btn btn--champ btn--lg" type="submit" style={{ width: "100%" }}>Send request</button>
                </div>
              </form>
            }
          </div>
        </div>
      </section>
    </div>);

}
window.PrivateEventView = PrivateEventView;
