/* eslint-disable */
// ============================================================================
// TRUST YOUR FAMILY — Event page components
// ============================================================================
const { useState, useRef } = React;

/* --- icons (simple line glyphs) ----------------------------------------- */
const I = {
  cal: (p) => (<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="3" y="4.5" width="18" height="16" rx="2.5"/><path d="M3 9h18M8 2.5v4M16 2.5v4"/></svg>),
  pin: (p) => (<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 21s7-6.2 7-11a7 7 0 1 0-14 0c0 4.8 7 11 7 11Z"/><circle cx="12" cy="10" r="2.6"/></svg>),
  clock: (p) => (<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="12" cy="12" r="9"/><path d="M12 7.5V12l3 2"/></svg>),
  people: (p) => (<svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="9" cy="8" r="3.2"/><path d="M2.5 19c.6-3.2 3.2-5 6.5-5s5.9 1.8 6.5 5"/><path d="M16.5 5.2a3 3 0 0 1 0 5.6M18 14.2c2.3.5 3.9 2 4.4 4.3"/></svg>),
  hands: (p) => (<svg width="22" height="20" viewBox="0 0 28 22" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M2 11.5 7 7l3.5 3 3-2.5L20 12"/><path d="M2 11.5l3.5 3.2a2 2 0 0 0 2.7-.1L12 11l3 2.6a2 2 0 0 0 2.7 0L26 9.5"/></svg>),
  arrow: (p) => (<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M5 12h14M13 6l6 6-6 6"/></svg>),
  back: (p) => (<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M19 12H5M11 6l-6 6 6 6"/></svg>),
  plus: (p) => (<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" {...p}><path d="M12 5v14M5 12h14"/></svg>),
  check: (p) => (<svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M20 6 9 17l-5-5"/></svg>),
  ext: (p) => (<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M14 5h5v5M19 5l-8 8M11 5H6a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2v-5"/></svg>),
};

/* --- helpers ------------------------------------------------------------- */
function fullAddress(ev) {
  return [ev.location.venue, ev.location.street, ev.location.cityState].filter(Boolean).join(", ");
}
function icsStamp(s) { return new Date(s).toISOString().replace(/[-:]/g, "").replace(/\.\d{3}/, ""); }
function downloadICS(ev) {
  const body = [
    "BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//Trust Your Family//Events//EN",
    "BEGIN:VEVENT", `UID:${window.eventSlug(ev)}@trustyourfamily.com`, `DTSTAMP:${icsStamp(new Date())}`,
    `DTSTART:${icsStamp(ev.date.start)}`, `DTEND:${icsStamp(ev.date.end)}`,
    `SUMMARY:${ev.title.lead} ${ev.title.accent}`,
    `LOCATION:${fullAddress(ev).replace(/,/g, "\\,")}`,
    `DESCRIPTION:${(ev.tagline || "").replace(/,/g, "\\,")}`,
    "END:VEVENT", "END:VCALENDAR",
  ].join("\r\n");
  const url = URL.createObjectURL(new Blob([body], { type: "text/calendar" }));
  const a = document.createElement("a");
  a.href = url; a.download = `${window.eventSlug(ev)}.ics`; a.click();
  setTimeout(() => URL.revokeObjectURL(url), 1500);
}

/* --- top bar ------------------------------------------------------------- */
function TopBar({ ev }) {
  return (
    <header className="topbar">
      <div className="wrap topbar__in">
        <a className="brandmark" href="Events.html">
          <b>Trust Your Family</b><span>EVENTS</span>
        </a>
        <div className="topbar__spacer" />
        <nav className="topnav">
          <a className="muted label-hide" href="Events.html"><span style={{display:'inline-flex'}}>{I.back()}</span> All events</a>
          {ev.status === "upcoming"
            ? <span className="status-pill"><span className="dot" /> Upcoming</span>
            : <span className="status-pill" style={{ color: "var(--muted)", background: "var(--navy-tint)" }}>Past event</span>}
          <a className="btn" href="#rsvp">RSVP</a>
        </nav>
      </div>
    </header>
  );
}

/* --- hero ---------------------------------------------------------------- */
function Hero({ ev, heroLeft }) {
  const art = (
    <div className="hero__art">
      <figure className="photo-card">
        <img src={ev.hero.image} alt={ev.hero.caption || "Event"} />
        {ev.hero.caption && <figcaption className="cap">{ev.hero.caption}</figcaption>}
      </figure>
      {ev.presenter && (
        <div className="presenter">
          <span className="pl">In partnership with</span>
          <img src={ev.presenter.logo} alt={ev.presenter.name} />
        </div>
      )}
    </div>
  );
  const text = (
    <div className="hero__text">
      <h1>{ev.title.lead}<span className="accent">{ev.title.accent}</span></h1>
      <span className="eyebrow audience-tag">{ev.audience}</span>
      <div className="hero__rule"><i /><span>{I.hands()}</span><i /></div>
      <p className="tagline">{ev.tagline}</p>
      <div className="meta">
        <div className="meta__row">
          <span className="meta__ic">{I.cal()}</span>
          <div><div className="lead">{ev.date.display} · {ev.date.timeDisplay}</div></div>
        </div>
        <div className="meta__row">
          <span className="meta__ic">{I.pin()}</span>
          <div>
            {ev.location.venue && <div className="sub">{ev.location.venue}</div>}
            <div className="sub">{ev.location.street}</div>
            <div className="sub dim">{ev.location.cityState}</div>
          </div>
        </div>
      </div>
      <div className="hero__cta">
        <a className="btn" href="#rsvp">RSVP to attend {I.arrow()}</a>
      </div>
    </div>
  );
  return (
    <section className="hero">
      <div className="wrap hero__grid">
        {heroLeft ? <>{art}{text}</> : <>{text}{art}</>}
      </div>
    </section>
  );
}

/* --- story --------------------------------------------------------------- */
function Story({ ev }) {
  if (!ev.story) return null;
  return (
    <section className="section story-wrap">
      <div className="wrap">
        <blockquote className="story">
          <span className="qmark">“</span>
          <p>{ev.story}</p>
        </blockquote>
      </div>
    </section>
  );
}

/* --- timeline ------------------------------------------------------------ */
function Timeline({ ev }) {
  if (!ev.timeline || !ev.timeline.length) return null;
  return (
    <section className="timeline-sec">
      <div className="wrap">
        <div className="kicker" style={{ justifyContent: "center" }}>{ev.timelineHeading || "How it came together"}</div>
        <div className="timeline">
          {ev.timeline.map((t, i) => (
            <div className={"tl-row" + (t.highlight ? " is-highlight" : "")} key={i}>
              <div className="tl-date">{t.date}</div>
              <div className="tl-rail"><span className="tl-dot" /></div>
              <div className="tl-body">{t.text}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* --- details + rsvp ------------------------------------------------------ */
function Facts({ ev }) {
  const mapSrc = `https://maps.google.com/maps?q=${encodeURIComponent(fullAddress(ev))}&z=15&output=embed`;
  const mapLink = `https://maps.google.com/maps?q=${encodeURIComponent(fullAddress(ev))}`;
  return (
    <div className="card">
      <div className="card__pad">
        <h3>Event details</h3>
        <p className="sub">Everything you need to know before you arrive.</p>
        <div className="facts">
          <div className="fact"><span className="fi">{I.cal()}</span><div><div className="fk">Date</div><div className="fv">{ev.date.display}</div></div></div>
          <div className="fact"><span className="fi">{I.clock()}</span><div><div className="fk">Time</div><div className="fv"><span className="em">{ev.date.timeDisplay}</span></div></div></div>
          <div className="fact"><span className="fi">{I.pin()}</span><div><div className="fk">Location</div><div className="fv">{ev.location.street}<br />{ev.location.cityState}</div></div></div>
          {ev.presenter && <div className="fact"><span className="fi">{I.people()}</span><div><div className="fk">Hosted by</div><div className="fv">{ev.presenter.name} <span style={{color:'var(--muted)',fontWeight:600}}>· {ev.presenter.sub}</span></div></div></div>}
        </div>
      </div>
      <div className="map-wrap">
        <div className="map-fallback" aria-hidden="true">
          <span className="mpin"></span>
          <span className="maddr">{ev.location.cityState}</span>
        </div>
        <iframe className="map" title="Event location map" src={mapSrc} loading="lazy"></iframe>
      </div>
      <a className="map-link" href={mapLink} target="_blank" rel="noopener">Open in Google Maps {I.ext()}</a>
    </div>
  );
}

function RSVP({ ev }) {
  const [f, setF] = useState({ first: "", last: "", goBy: "", email: "", phone: "", company: "", guests: 1, smsOk: "", newsOk: "", notes: "" });
  const [err, setErr] = useState({});
  const [sent, setSent] = useState(false);
  const [status, setStatus] = useState("idle"); // idle | sending | error
  const set = (k, v) => setF((s) => ({ ...s, [k]: v }));

  // Zoho Web-to-Lead — active only once actionUrl is filled in events-data.js.
  const w2l = ev.rsvp && ev.rsvp.webToLead && ev.rsvp.webToLead.actionUrl ? ev.rsvp.webToLead : null;
  const descRef = useRef(null);
  const companyRef = useRef(null);
  const submittedRef = useRef(false);

  function validate() {
    const er = {};
    if (!f.first.trim()) er.first = "Please enter your first name.";
    if (!f.goBy.trim()) er.goBy = "Let us know what to call you.";
    if (!f.last.trim()) er.last = "Please enter your last name.";
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(f.email)) er.email = "Enter a valid email.";
    if (f.phone.replace(/\D/g, "").length < 10) er.phone = "Enter a valid phone number.";
    if (!f.smsOk) er.smsOk = "Please choose Yes or No.";
    if (!f.newsOk) er.newsOk = "Please choose Yes or No.";
    return er;
  }

  async function submit(e) {
    const er = validate();
    setErr(er);
    if (Object.keys(er).length) { e.preventDefault(); return; }

    const endpoint = ev.rsvp && ev.rsvp.endpoint;

    // Path A — Catalyst function (PREFERRED). It find-or-creates the person,
    // creates ONE linked Meetings/Events record per RSVP, and fires Email + SMS.
    // The payload carries the event's identity so the function knows WHICH
    // event this is, without any guessing:
    //   slug         -> Event_ID   (stable per-event key, e.g. "jun-12-2026")
    //   eventTitle   -> Event_Title
    //   eventDate    -> Start_DateTime   (eventEnd -> End_DateTime)
    if (endpoint) {
      e.preventDefault();
      setStatus("sending");
      const payload = {
        ...f,
        eventTitle:   `${ev.title.lead} ${ev.title.accent}`.trim(),
        slug:         window.eventSlug(ev),
        eventDate:    (ev.date && ev.date.start) || "",
        eventEnd:     (ev.date && ev.date.end) || "",
        eventDisplay: (ev.date && ev.date.display) || "",
      };
      try {
        // The Catalyst function reliably creates the CRM Lead + Event, but its
        // cross-origin response isn't readable from the browser (the endpoint is
        // an authenticated Advanced I/O function). So submit fire-and-forget:
        // send the RSVP with mode:"no-cors", then show the success card. A
        // genuine network failure still throws and surfaces the error message.
        await fetch(endpoint, {
          method: "POST",
          mode: "no-cors",
          headers: { "Content-Type": "text/plain;charset=UTF-8" },
          body: JSON.stringify(payload),
        });
        setSent(true);
      } catch (e2) {
        setStatus("error");
      }
      return;
    }

    // Path B — Zoho Web-to-Lead native POST (fallback until the Catalyst
    // endpoint is filled in). Posts into a hidden iframe so the page never
    // navigates and we keep the designed success card.
    if (w2l) {
      if (companyRef.current) companyRef.current.value = f.company.trim() || `${f.first} ${f.last}`.trim();
      if (descRef.current) {
        const lines = [];
        lines.push("Guests attending: " + f.guests);
        lines.push("Event: " + `${ev.title.lead} ${ev.title.accent}`.trim());
        if (f.notes.trim()) lines.push("Notes: " + f.notes.trim());
        descRef.current.value = lines.join("\n");
      }
      submittedRef.current = true;
      setStatus("sending");
      return; // do NOT preventDefault — the native POST proceeds to the iframe
    }

    // Path C — simulate (prototype, no backend configured).
    e.preventDefault();
    setStatus("sending");
    await new Promise((res) => setTimeout(res, 700)); // demo latency
    setSent(true);
  }

  if (sent) return (
    <div className="card" id="rsvp">
      <div className="card__pad rsvp-success">
        <div className="check">{I.check()}</div>
        <h3>You’re on the list</h3>
        <p>Thank you, {f.goBy.trim() || f.first.trim()}. A confirmation for <strong>{ev.title.lead} {ev.title.accent}</strong> is headed to {f.email}. We look forward to seeing you on {ev.date.display}.</p>
      </div>
    </div>
  );

  return (
    <div className="card" id="rsvp">
      <div className="card__pad">
        <h3>RSVP</h3>
        <p className="sub">{ev.rsvp.note}</p>
        <form className="form" onSubmit={submit} noValidate
          action={w2l ? w2l.actionUrl : undefined}
          method={w2l ? "POST" : undefined}
          target={w2l ? "tyf_w2l_iframe" : undefined}
          acceptCharset="UTF-8">
          {w2l && (
            <div style={{ display: "none" }} aria-hidden="true">
              <input type="hidden" name="xnQsjsdp" value={w2l.xnQsjsdp || ""} readOnly />
              <input type="hidden" name="xmIwtLD" value={w2l.xmIwtLD || ""} readOnly />
              <input type="hidden" name="actionType" value="TGVhZHM=" readOnly />
              <input type="hidden" name="returnURL" value={w2l.returnUrl || ""} readOnly />
              <input type="hidden" name="Lead Source" value={w2l.leadSource || "Web Download"} readOnly />
              <input type="hidden" name="LEADCF185" value="N/A" readOnly />
              <input type="hidden" name="aG9uZXlwb3Q" value="" readOnly />
              <input type="hidden" name="Company" ref={companyRef} />
              <input type="hidden" name="Description" ref={descRef} />
            </div>
          )}
          {w2l && (
            <iframe name="tyf_w2l_iframe" title="RSVP submission" style={{ display: "none" }}
              onLoad={() => { if (submittedRef.current) setSent(true); }} />
          )}
          <div className="row-2">
            <div className="field">
              <label>First name <span className="req">*</span></label>
              <input className={"input" + (err.first ? " bad" : "")} name={w2l ? "First Name" : undefined} value={f.first} onChange={(e) => set("first", e.target.value)} placeholder="Jane" />
              {err.first && <span className="err">{err.first}</span>}
            </div>
            <div className="field">
              <label>Last name <span className="req">*</span></label>
              <input className={"input" + (err.last ? " bad" : "")} name={w2l ? "Last Name" : undefined} value={f.last} onChange={(e) => set("last", e.target.value)} placeholder="Doe" />
              {err.last && <span className="err">{err.last}</span>}
            </div>
          </div>
          <div className="row-2">
            <div className="field">
              <label>Go By Name <span className="req">*</span></label>
              <input className={"input" + (err.goBy ? " bad" : "")} name={w2l ? "LEADCF45" : undefined} value={f.goBy} onChange={(e) => set("goBy", e.target.value)} placeholder="What we'll call you" />
              {err.goBy && <span className="err">{err.goBy}</span>}
            </div>
            <div className="field">
              <label>Phone <span className="req">*</span> <span className="hint">mobile preferred</span></label>
              <input className={"input" + (err.phone ? " bad" : "")} name={w2l ? "Phone" : undefined} type="tel" value={f.phone} onChange={(e) => set("phone", e.target.value)} placeholder="(555) 123-4567" />
              {err.phone && <span className="err">{err.phone}</span>}
            </div>
          </div>
          <div className="row-2">
            <div className="field">
              <label>Email <span className="req">*</span></label>
              <input className={"input" + (err.email ? " bad" : "")} name={w2l ? "Email" : undefined} type="email" value={f.email} onChange={(e) => set("email", e.target.value)} placeholder="jane@firm.com" />
              {err.email && <span className="err">{err.email}</span>}
            </div>
            <div className="field">
              <label>Company / role</label>
              <input className="input" value={f.company} onChange={(e) => set("company", e.target.value)} placeholder="Optional" />
            </div>
          </div>
          <div className="field">
            <label>Guests attending</label>
            <div className="stepper">
              <button type="button" onClick={() => set("guests", Math.max(1, f.guests - 1))} aria-label="Fewer">–</button>
              <input value={f.guests} readOnly aria-label="Guests" />
              <button type="button" onClick={() => set("guests", Math.min(10, f.guests + 1))} aria-label="More">+</button>
            </div>
          </div>
          <div className="field">
            <label>Anything we should know?</label>
            <textarea className="input" value={f.notes} onChange={(e) => set("notes", e.target.value)} placeholder="A plus-one’s name, a question…"></textarea>
          </div>
          <div className={"consentq" + (err.smsOk ? " bad" : "")}>
            <div className="consentq__txt"><b>Text me event reminders.</b> <span className="req">*</span> I agree to receive an SMS confirmation and reminders about this event at the number above. Message &amp; data rates may apply; reply STOP to opt out.</div>
            <div className="consentq__opts">
              <label className={"radiopill" + (f.smsOk === "Yes" ? " on" : "")}>
                <input type="radio" name={w2l ? "SMS_Opt_In" : "smsOk"} value="Yes" checked={f.smsOk === "Yes"} onChange={() => set("smsOk", "Yes")} /> Yes
              </label>
              <label className={"radiopill" + (f.smsOk === "No" ? " on" : "")}>
                <input type="radio" name={w2l ? "SMS_Opt_In" : "smsOk"} value="No" checked={f.smsOk === "No"} onChange={() => set("smsOk", "No")} /> No
              </label>
            </div>
            {err.smsOk && <span className="err">{err.smsOk}</span>}
          </div>
          <div className={"consentq" + (err.newsOk ? " bad" : "")}>
            <div className="consentq__txt"><b>Subscribe to our weekly newsletter.</b> <span className="req">*</span> Get estate-planning insights and event invitations from Trust Your Family in your inbox.</div>
            <div className="consentq__opts">
              <label className={"radiopill" + (f.newsOk === "Yes" ? " on" : "")}>
                <input type="radio" name={w2l ? "Newletter_Opt_In_2" : "newsOk"} value="Yes" checked={f.newsOk === "Yes"} onChange={() => set("newsOk", "Yes")} /> Yes
              </label>
              <label className={"radiopill" + (f.newsOk === "No" ? " on" : "")}>
                <input type="radio" name={w2l ? "Newletter_Opt_In_2" : "newsOk"} value="No" checked={f.newsOk === "No"} onChange={() => set("newsOk", "No")} /> No
              </label>
            </div>
            {err.newsOk && <span className="err">{err.newsOk}</span>}
          </div>
          {ev.rsvp.deadlineDisplay && <div className="deadline">{ev.rsvp.deadlineDisplay}</div>}
          {status === "error" && <div className="form-error" role="alert">Something went wrong sending your RSVP. Please try again, or email <a href={`mailto:${ev.rsvp.contactEmail}`}>{ev.rsvp.contactEmail}</a>.</div>}
          <button className="btn btn--block" type="submit" disabled={status === "sending"}>{status === "sending" ? "Sending…" : <>Confirm my RSVP {I.arrow()}</>}</button>
          <div className="form-note">{I.pin({width:15,height:15,style:{flex:'0 0 auto',marginTop:2}})}<span>Questions? Email <a style={{color:'var(--orange-deep)',fontWeight:700}} href={`mailto:${ev.rsvp.contactEmail}`}>{ev.rsvp.contactEmail}</a></span></div>
        </form>
      </div>
    </div>
  );
}

function DetailsAndRSVP({ ev }) {
  return (
    <section className="section" style={{ paddingTop: 46, paddingBottom: 8 }}>
      <div className="wrap">
        <div className="kicker" style={{ justifyContent: "center", marginBottom: 30 }}>Attend the preview</div>
        <div className="dr-grid">
          <Facts ev={ev} />
          {ev.rsvp && ev.rsvp.enabled && <RSVP ev={ev} />}
        </div>
      </div>
    </section>
  );
}

/* --- invite + partners --------------------------------------------------- */
function InviteBand({ ev }) {
  if (!ev.invite) return null;
  return (
    <section className="section" style={{ paddingTop: 36 }}>
      <div className="wrap">
        <div className="invite-band">
          <span className="ii">{I.people()}</span>
          <p>{ev.invite}</p>
        </div>
      </div>
    </section>
  );
}

function Partners({ ev }) {
  if (!ev.partners || !ev.partners.length) return null;
  return (
    <footer className="partners">
      <div className="partners__band">Thank you to our partners</div>
      <div className="partners__logos">
        {ev.partners.map((p, i) => <img key={i} src={p.logo} alt={p.name} title={p.name} />)}
      </div>
      <div className="colophon">© {new Date().getFullYear()} Trust Your Family · Keep Your Promise. Secure Your Legacy. · <a href="Events.html">All events</a></div>
    </footer>
  );
}

/* --- page ---------------------------------------------------------------- */
function EventPage({ ev, tweaks }) {
  return (
    <>
      <TopBar ev={ev} />
      <Hero ev={ev} heroLeft={tweaks && tweaks.heroLeft} />
      <Story ev={ev} />
      <Timeline ev={ev} />
      <DetailsAndRSVP ev={ev} />
      <InviteBand ev={ev} />
      <Partners ev={ev} />
    </>
  );
}

Object.assign(window, { I, EventPage, TopBar, Hero, Story, Timeline, DetailsAndRSVP, InviteBand, Partners, downloadICS, fullAddress });
