/* global React */
const { useState: useStateB, useEffect: useEffectB, useRef: useRefB } = React;

/* ============ Interactive Map of Patagonia ============ */
function PatagoniaMap() {
  const [active, setActive] = useStateB("torres");
  const lodges = {
    torres: {
      name: "Explora Torres del Paine",
      tag: "Patagonia, Chile",
      desc: "A lakefront 50-room perch inside Torres del Paine National Park, overlooking the shimmering expanse of Lake Pehoé with dramatic, uninterrupted views of the iconic Torres and Cuernos massifs.",
      url: "https://www.explora.com/lodge/torres-del-paine-lodge/",
      img: "images/lodge-tdp.jpg",
      x: 43.4, y: 64.8
    },
    reserve: {
      name: "Explora Torres del Paine Conservation Reserve",
      tag: "Conservation reserve · Patagonia, Chile",
      desc: "An intimate 10-room refuge set exclusively within our own 14,000-acre private reserve, a rare wilderness sanctuary where the land is as carefully tended as the experience itself.",
      url: "https://www.explora.com/lodge/torres-del-paine-conservation-reserve/",
      img: "images/lodge-reserve.jpg",
      x: 40.6, y: 58.7
    },
    pnp: {
      name: "Explora Patagonia National Park",
      tag: "Patagonia National Park, Aysén",
      desc: "A storied 13-room lodge inside Patagonia National Park, built on land restored through the legendary conservation vision of Doug and Kris Tompkins. Prime territory for puma sightings, abundant wildlife, and world-class fly fishing on pristine Patagonian rivers.",
      url: "https://www.explora.com/lodge/patagonia-national-park/",
      img: "images/lodge-pnp-stone.png",
      x: 42.7, y: 23.2
    },
    chalten: {
      name: "Explora El Chaltén",
      tag: "Patagonia, Argentina",
      desc: "A secluded 20-room retreat at the foot of the shimmering Eléctrico Valley, steps from the peaks that made El Chaltén the mountaineering capital of Argentina – where Cerro Torre and Fitz Roy draw climbers and trekkers from around the world.",
      url: "https://www.explora.com/el-chalten-lodge/",
      img: "images/lodge-chalten.jpg",
      x: 44.1, y: 54.4
    },
    calafate: {
      name: "Explora El Calafate",
      tag: "Perito Moreno - Patagonia, Argentina",
      desc: "20 rooms on an expansive working estancia steeped in deep Gaucho culture, offering horseback riding across open steppe, distant views of the thundering Perito Moreno Glacier, and a landscape rich with raw Paleolithic history near the Southern Patagonia Ice Field.",
      url: "https://www.explora.com/lodge/el-calafate/",
      img: "images/lodge-calafate.jpg",
      x: 48.7, y: 60.3
    },
    fuego: {
      name: "Explora Tierra del Fuego Expedition",
      tag: "Tierra del Fuego · Patagonia · 7 days · Limited to 8 travelers",
      desc: "From windswept Pampas to the frozen glaciers of the far south, this 7-day expedition — limited to just 8 travelers — is for the adventurous traveler seeking to discover and explore further.",
      url: "https://www.explora.com/travel-tierra-del-fuego/",
      img: "images/tierra-del-fuego.png",
      x: 65.5, y: 87
    }
  };
  const a = lodges[active];

  return (
    <section className="map-sec">
      <div className="container">
        <div className="section-head">
          <div className="eyebrow" style={{ color: "#666666", fontSize: "13px" }}>Where we are</div>
          <h2 className="serif section-head__title">The Largest Network of Lodges in Patagonia.</h2>
          <p className="section-head__lede">

          </p>
        </div>

        <div className="map-sec__layout">
          <div className="map-sec__canvas">
            <div className="map-sec__wrap">
              <img src="images/mapa-pat-network.png" alt="Patagonia network map" className="map-sec__img" />
              {Object.entries(lodges).map(([key, l]) =>
              <button
                key={key}
                type="button"
                onClick={() => setActive(key)}
                className={"map-pin-btn " + (active === key ? "is-active" : "")}
                style={{ left: `${l.x}%`, top: `${l.y}%` }}
                aria-label={l.name}>
                  <span className="map-pin-btn__ring" />
                  {active === key &&
                <span className="map-pin-btn__popup">
                      <img src={l.img} alt="" />
                      <span className="map-pin-btn__popup-name">{l.name.replace("Explora ", "")}</span>
                    </span>
                }
                </button>
              )}
            </div>
          </div>

          <div className="map-sec__info">
            <div className="eyebrow">{a.tag}</div>
            <h3 className="serif map-sec__name">{a.name}</h3>
            {a.desc && <p className="map-sec__desc" style={{ fontFamily: '"Objektiv MK1", "Inter", sans-serif', fontSize: "14px", lineHeight: 1.5, margin: "6px 0 14px" }}>{a.desc}</p>}
            {a.url && <a href={a.url} target="_blank" rel="noopener" className="link-arrow map-sec__cta" style={{ color: "#fff", backgroundColor: "#000", fontFamily: "\"Objektiv MK1\"", borderStyle: "solid", borderColor: "#000", borderWidth: "1px", opacity: "1", display: "inline-flex", alignItems: "center", gap: "8px", margin: "10px 0px 20px", padding: "10px 16px" }}>Discover the expedition <Icon.Arrow size={12} /></a>}
            <div className="map-sec__list">
              {Object.entries(lodges).map(([key, l]) =>
              <button key={key}
              className={"map-sec__row " + (active === key ? "is-active" : "")}
              onClick={() => setActive(key)}>
                  <span className="map-sec__dot" />
                  <span className="objektiv map-sec__rowname">{l.name}</span>
                  <Icon.Arrow size={12} />
                </button>
              )}
            </div>
          </div>
        </div>
      </div>
    </section>);

}

/* ============ FAQ ============ */
function FAQ() {
  const items = [
  { q: "When is the best time to travel to Patagonia?",
    a: "The most popular time to visit is during the summer months of December to February, with mild temperatures and full access to our explorations. Spring and autumn shoulder seasons are equally compelling, with fewer crowds, extraordinary light, and wildflowers or fall foliage depending on the time of year." },
  { q: "What is included in the all-inclusive rate?",
    a: "All meals and beverages, daily guided explorations, expert bilingual guides, lodge amenities, and round-trip airport transfers at pre-scheduled times." },
  { q: "What is the level of fitness required?",
    a: "Our explorations span every level, from gentle riverside walks to full-day treks. You design your days alongside our guides, day by day, based on weather and how you feel." },
  { q: "Can I combine multiple lodges in one journey?",
    a: "Yes. Our unique network of lodges allows you to seamlessly combine multiple destinations into one journey, experiencing Patagonia as a vast, borderless region. With over 30 years of expertise, travelers can connect stays across Chile and Argentina — and even Tierra del Fuego — into one authentic, multi-destination adventure." },
  { q: "What is your cancellation policy?",
    a: <span>See full conditions at <a href="https://www.explora.com/payment-and-cancellation-policies/" target="_blank" rel="noopener" style={{ textDecoration: "underline", color: "rgb(51, 51, 51)" }}>explora.com/payment-and-cancellation-policies</a>.</span> }];

  const [open, setOpen] = useStateB(0);
  return (
    <section className="faq">
      <div className="container">
        <div className="faq__layout">
          <div className="faq__head">
            <div className="eyebrow" style={{ color: "#666666", fontSize: "13px" }}>Before you go</div>
            <h2 className="serif faq__title">Questions, Answered.</h2>
            <p className="faq__lede">


            </p>
          </div>
          <div className="faq__list">
            {items.map((it, i) =>
            <div key={i} className={"faq__item " + (open === i ? "is-open" : "")}>
                <button className="faq__q" onClick={() => setOpen(open === i ? -1 : i)}>
                  <span className="serif">{it.q}</span>
                  <span className="faq__icon">{open === i ? <Icon.Minus size={14} /> : <Icon.Plus size={14} />}</span>
                </button>
                {open === i && <div className="faq__a">{it.a}</div>}
              </div>
            )}
          </div>
        </div>
      </div>
    </section>);

}

/* ============ Lead capture (final CTA) ============ */
function LeadForm() {
  const [submitted, setSubmitted] = useStateB(false);
  const [submitting, setSubmitting] = useStateB(false);
  const [errorMsg, setErrorMsg] = useStateB("");
  const submit = async (e) => {
    e.preventDefault();
    const formEl = e.currentTarget;
    const data = Object.fromEntries(new FormData(formEl).entries());

    // Combine month + year into a single travel_dates field for downstream systems
    if (data.travel_month || data.travel_year) {
      data.travel_dates = [data.travel_month, data.travel_year].filter(Boolean).join(" ");
    }

    setSubmitting(true);
    setErrorMsg("");
    try {
      const res = await fetch("https://formspree.io/f/mrejzayv", {
        method: "POST",
        headers: { "Accept": "application/json", "Content-Type": "application/json" },
        body: JSON.stringify({
          ...data,
          _subject: `New Patagonia lead — ${data.name || "Unknown"}`,
          _source: "Patagonia Landing Page"
        })
      });
      if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        throw new Error(body.error || `Submission failed (${res.status})`);
      }
    } catch (err) {
      console.error("Formspree submission failed:", err);
      setSubmitting(false);
      setErrorMsg("We couldn't send your request. Please try again, or email reservations@explora.com.");
      return;
    }

    // Notify OptinMonster of conversion + pass lead data through the OM API
    try {
      if (window.om && typeof window.om.trigger === "function") {
        window.om.trigger("ExploraLeadFormSubmit", data);
      }
      // Standard OM conversion event — picked up by their analytics
      document.dispatchEvent(new CustomEvent("om.Conversion", { detail: data }));
      // Also push to dataLayer for any GTM/GA pipelines
      if (window.dataLayer) {
        window.dataLayer.push({ event: "lead_form_submit", ...data });
      }
      if (typeof window.gtag === "function") {
        window.gtag("event", "form_submit", {
          form_name: "lead_inquiry",
          form_location: "bottom",
          travel_window: data.travel_window,
          group_size: data.group_size,
          interest: data.interest
        });
      }
    } catch (err) {
      console.warn("OM tracking failed:", err);
    }

    setSubmitting(false);
    setSubmitted(true);
  };
  return (
    <section className="lead" id="inquiry">
      <div className="lead__bg photo photo--img">
        <img src="images/caballos.jpg" alt="Riders at sunset in Patagonia" />
      </div>
      <div className="container lead__container">
        <div className="lead__card">
          {submitted ?
          <div className="lead__success">
              <div className="lead__check"><Icon.Check size={28} /></div>
              <h2 className="serif lead__success-title">Your Patagonia journey begins.</h2>
              <p className="lead__success-text">
                A travel designer will reach out within 48 hours with lodge availability and
                a personalized proposal, including the early-booking offer reserved for you.
              </p>
              <a href="#lodges" className="lead__success-cta">
                While you wait, explore our lodges <Icon.Arrow size={12} />
              </a>
            </div> :

          <>
              <div className="lead__intro">
                <div className="lead__offer-badge">
                  <span className="lead__offer-dot" aria-hidden="true"></span>
                  <span>Limited availability · book early to secure your dates</span>
                </div>
                <h2 className="serif lead__title">Be first in line for 2027 availability and exclusive offers.</h2>
                <p className="lead__lede">Our lodges are intentionally small and peak-season dates fill up months in advance. Sign up and a travel designer will reach out with current availability and a personalized proposal.</p>
                <ul className="lead__bullets">
                  <li><Icon.Check size={14} /> Priority access to peak-season dates</li>
                  <li><Icon.Check size={14} /> First word on early-booking fares &amp; multi-lodge offers</li>
                  <li><Icon.Check size={14} /> No spam, unsubscribe anytime</li>
                </ul>
              </div>
              <form className="lead__form" onSubmit={submit} aria-describedby="lead-required-note">
                <p id="lead-required-note" className="lead__required-note"><span aria-hidden="true">*</span> Indicates a required field</p>
                <div className="lead__row">
                  <div className="field field--dark">
                    <label htmlFor="lead-name">Full name <span className="req" aria-hidden="true">*</span><span className="sr-only"> required</span></label>
                    <input id="lead-name" required aria-required="true" type="text" name="name" placeholder="Your name" autoComplete="name" />
                  </div>
                  <div className="field field--dark">
                    <label htmlFor="lead-email">Email <span className="req" aria-hidden="true">*</span><span className="sr-only"> required</span></label>
                    <input id="lead-email" required aria-required="true" type="email" name="email" placeholder="you@email.com" autoComplete="email" />
                  </div>
                </div>
                <div className="lead__row">
                  <div className="field field--dark">
                    <label htmlFor="lead-phone">Phone</label>
                    <input id="lead-phone" type="tel" name="phone" placeholder="+1 555 000 0000" autoComplete="tel" />
                  </div>
                  <div className="field field--dark">
                    <label htmlFor="lead-month">Approx. travel date</label>
                    <div className="lead__date-row">
                      {(() => {
                      const now = new Date();
                      const curYear = now.getFullYear();
                      const curMonth = now.getMonth(); // 0-indexed
                      const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
                      const years = [curYear, curYear + 1, curYear + 2];
                      return (
                        <>
                            <select id="lead-month" name="travel_month" defaultValue="" aria-label="Travel month" data-current-month={curMonth} data-current-year={curYear}>
                              <option value="" disabled>Month</option>
                              {monthNames.map((m, i) => <option key={m} value={m} data-month-index={i}>{m}</option>)}
                            </select>
                            <select name="travel_year" defaultValue="" aria-label="Travel year" onChange={(e) => {
                            const monthSel = document.getElementById('lead-month');
                            const selectedYear = parseInt(e.target.value, 10);
                            if (!monthSel) return;
                            [...monthSel.options].forEach((opt) => {
                              const mi = parseInt(opt.dataset.monthIndex, 10);
                              if (Number.isNaN(mi)) return;
                              const isPast = selectedYear === curYear && mi < curMonth;
                              opt.disabled = isPast;
                              opt.style.color = isPast ? '#bbb' : '';
                            });
                            // If currently-selected month is now disabled, clear it
                            const cur = monthSel.selectedOptions[0];
                            if (cur && cur.disabled) monthSel.value = '';
                          }}>
                              <option value="" disabled>Year</option>
                              {years.map((y) => <option key={y} value={y}>{y}</option>)}
                            </select>
                          </>);

                    })()}
                    </div>
                  </div>
                </div>
                <div className="field field--dark">
                  <label htmlFor="lead-lodge">Lodge of interest</label>
                  <select id="lead-lodge" name="lodge" defaultValue="">
                    <option value="" disabled>Select a lodge, or let us recommend</option>
                    <option>Explora Torres del Paine</option>
                    <option>Explora El Chaltén</option>
                    <option>Explora El Calafate</option>
                    <option>Multi-lodge journey</option>
                    <option>I'm not sure yet, recommend for me</option>
                  </select>
                </div>
                <div className="lead__cta-row">
                  <button type="submit" className="btn lead__submit" disabled={submitting} style={submitting ? { opacity: 0.6, cursor: "wait" } : undefined}>
                    {submitting ? "Sending…" : <>Keep Me Posted <Icon.Arrow size={12} /></>}
                  </button>
                  <span className="lead__fineprint">
                    By submitting, you agree to receive communications from Explora. We will never share your details.
                  </span>
                </div>
                {errorMsg &&
              <p role="alert" style={{ marginTop: 12, color: "#c0392b", fontSize: 14, fontFamily: '"Objektiv MK1", "Inter", sans-serif' }}>
                    {errorMsg}
                  </p>
              }
              </form>
            </>}
        </div>
      </div>
    </section>);
}

/* ============ Footer ============ */
function SiteFooter() {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer__top">
          <div className="footer__brand">
            <a href="https://www.explora.com/" target="_blank" rel="noopener" className="serif footer__logo" aria-label="Explora — visit explora.com"></a>
            <p className="footer__tag">Discover an award-winning collection of lodges and expeditions in iconic destinations.</p>
            <div className="footer__follow">
              <span className="footer__follow-eyebrow">Follow our journey</span>
              <span className="footer__follow-text">Wonder, wherever we are.</span>
            </div>
            <div className="footer__social">
              <a href="https://www.instagram.com/exploratravel" target="_blank" rel="noopener" aria-label="Instagram">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden="true">
                  <rect x="3" y="3" width="18" height="18" rx="5" />
                  <circle cx="12" cy="12" r="4" />
                  <circle cx="17.5" cy="6.5" r="1" fill="currentColor" stroke="none" />
                </svg>
                <span>Instagram</span>
              </a>
              <a href="https://www.youtube.com/user/exploratravel" target="_blank" rel="noopener" aria-label="YouTube">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
                  <path d="M23 7.2a3 3 0 0 0-2.1-2.1C19 4.5 12 4.5 12 4.5s-7 0-8.9.6A3 3 0 0 0 1 7.2 31 31 0 0 0 .5 12 31 31 0 0 0 1 16.8a3 3 0 0 0 2.1 2.1c1.9.6 8.9.6 8.9.6s7 0 8.9-.6a3 3 0 0 0 2.1-2.1 31 31 0 0 0 .5-4.8 31 31 0 0 0-.5-4.8zM10 15.5v-7l6 3.5z" />
                </svg>
                <span>YouTube</span>
              </a>
              <a href="https://cl.linkedin.com/company/explora" target="_blank" rel="noopener" aria-label="LinkedIn">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
                  <path d="M4.98 3.5a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5zM3 9.5h4v11H3v-11zM10 9.5h3.8v1.5h.05c.53-1 1.83-2 3.77-2 4.04 0 4.78 2.66 4.78 6.12V20.5h-4v-5.04c0-1.2-.02-2.74-1.67-2.74-1.67 0-1.93 1.3-1.93 2.65V20.5h-4v-11z" />
                </svg>
                <span>LinkedIn</span>
              </a>
            </div>
          </div>
          <div className="footer__cols">
            <div className="footer__col">
              <div className="eyebrow footer__heading">Destinations</div>
              <a href="https://www.explora.com/patagonia-travel-argentina-chile/" target="_blank" rel="noopener">Patagonia</a>
              <a href="https://www.explora.com/lodge/atacama-lodge/" target="_blank" rel="noopener">Atacama Desert</a>
              <a href="https://www.explora.com/lodge/easter-island-hotels/" target="_blank" rel="noopener">Easter Island</a>
              <a href="https://www.explora.com/lodge/travel-machupicchu-and-the-sacred-valley-of-the-incas-peru-explora/" target="_blank" rel="noopener">Sacred Valley</a>
              <a href="https://www.explora.com/lodge/atacama-uyuni-crossing/" target="_blank" rel="noopener">Bolivia</a>
            </div>
            <div className="footer__col">
              <div className="eyebrow footer__heading">EXPEDITIONS</div>
              <a href="https://www.explora.com/lodge/atacama-uyuni-crossing/" target="_blank" rel="noopener">Iceland</a>
              <a href="https://www.explora.com/explora-passport/" target="_blank" rel="noopener">Tierra del Fuego</a>
              <a href="https://www.explora.com/explora-connects-patagonia-lodge-to-lodge/" target="_blank" rel="noopener">Sacred Mountains</a>
            </div>
            <div className="footer__col">
              <div className="eyebrow footer__heading">About</div>
              <a href="https://www.explora.com/explora-travels/" target="_blank" rel="noopener">Our Philosophy</a>
              <a href="https://www.explora.com/explora-south-america/" target="_blank" rel="noopener">Sustainability</a>
              <a href="https://www.explora.com/explora-jobs/" target="_blank" rel="noopener">Work with Us</a>
              <a href="https://www.explora.com/press-page/" target="_blank" rel="noopener">Press / Newsroom</a>
              <a href="mailto:reserve@explora.com">Contact</a>
            </div>
            <div className="footer__col">
              <div className="eyebrow footer__heading">Reservations</div>
              <a href="tel:+18336992649">USA +1 (833) 991-9206</a>
              <a href="tel:+56223952800">Chile +56 2 2395 2800</a>
              <a href="mailto:reserve@explora.com">reserve@explora.com</a>
            </div>
          </div>
        </div>
        <div className="rule-dark" />
        <div className="footer__bottom">
          <div style={{ fontFamily: "\"Objektiv MK1\"" }}>© 2026 Explora.</div>
          <div className="footer__legal">
            <a href="https://www.explora.com/payment-and-cancellation-policies/" target="_blank" rel="noopener">Terms</a>
            <a href="https://www.explora.com/privacy-terms/" target="_blank" rel="noopener">Privacy</a>
          </div>
        </div>
      </div>
    </footer>);

}

/* ============ Stay & Explore (gallery) ============ */
function StayExplore() {
  const [lightbox, setLightbox] = useStateB(null);
  const tiles = [
  {
    src: "images/room-tdp.jpg",
    title: "Rooms that frame the wild",
    caption: "Picture windows opening to the landscape, every lodge sited so the view comes inside.",
    credit: "Accommodations at Explora Torres del Paine",
    tag: "Stay"
  },
  {
    src: "images/spa-cft.jpg",
    title: "Recovery, relaxation and connection",
    caption: "Wellness as the natural outcome of immersion, feel restored by nature, renewed through exploration.",
    credit: "Outdoor hot tubs and cold plunge pool at Explora El Calafate",
    tag: "Wellness"
  }];

  const bullets = [
  "Architecture that frames the landscape",
  "Everything included, nothing unnecessary",
  "Effortless comfort and connection after exploration"];

  return (
    <section className="stay">
      <div className="container stay__container">
        <div className="section-head">
          <div className="eyebrow" style={{ color: "#666666" }}></div>
          <h2 className="serif section-head__title">Luxury That Lets the
Destination Lead.</h2>
          <ul className="stay__bullets">
            {bullets.map((b, i) => <li key={i} className="stay__bullet">
                <span className="stay__bullet-mark" style={{ borderRadius: "10px" }} />
                <span>{b}</span>
              </li>
            )}
          </ul>
        </div>
        <div className="stay__grid">
          {tiles.map((t, i) =>
          <button key={i} className="stay__tile" onClick={() => setLightbox(t)}>
              <div className="photo photo--img stay__media">
                <img src={t.src} alt={t.title} />
                {t.credit && <span className="stay__credit">{t.credit}</span>}
              </div>
              <div className="stay__body">
                <div className="eyebrow stay__tag">{t.tag}</div>
                <div className="objektiv stay__title">{t.title}</div>
                <div className="stay__caption">{t.caption}</div>
              </div>
            </button>
          )}
        </div>
      </div>
      {lightbox &&
      <div className="stay__lightbox" onClick={() => setLightbox(null)}>
          <button className="stay__lightbox-close" onClick={() => setLightbox(null)}>×</button>
          <img src={lightbox.src} alt={lightbox.title} onClick={(e) => e.stopPropagation()} />
          <div className="stay__lightbox-cap">
            <div className="serif">{lightbox.title}</div>
            <div className="stay__lightbox-sub">{lightbox.caption}</div>
          </div>
        </div>
      }
    </section>);

}

Object.assign(window, { PatagoniaMap, FAQ, LeadForm, SiteFooter, StayExplore });