/* Imlil Trips Morocco — gallery, reviews, about, reservation, footer, fixed contact */

const DS = window.IMLIL_DATA;

/* ---------- photo gallery + lightbox ---------- */
function GallerySection({ lightboxIndex, setLightboxIndex }) {
  const { t, p } = useLang();
  const [filter, setFilter] = React.useState("all");
  const filters = [
    { id: "all", label: t("gallery_all") },
    ...DS.tours.map((tour) => ({ id: tour.id, label: p(tour.name) })),
    { id: "moments", label: t("gallery_moments") }
  ];
  const photos = DS.photos.filter((ph) => filter === "all" || ph.tour === filter);
  return (
    <section className="section" id="photos" data-screen-label="Photos">
      <FadeGroup>
        <div className="section-head">
          <p className="eyebrow">{t("gallery_eyebrow")}</p>
          <h2>{t("gallery_title")}</h2>
          <p className="sub">{t("gallery_sub")}</p>
        </div>
        <div className="filter-row" role="tablist" aria-label={t("filter_photos")}>
          {filters.map((f) => (
            <button key={f.id} className={"filter-btn" + (filter === f.id ? " active" : "")} onClick={() => setFilter(f.id)}>
              {f.label}
            </button>
          ))}
        </div>
        <div className="masonry">
          {photos.map((ph) => (
            <button key={ph.src} aria-label={p(ph.alt)} onClick={() => setLightboxIndex(DS.photos.indexOf(ph))}>
              <img src={ph.src} alt={p(ph.alt)} loading="lazy" />
            </button>
          ))}
        </div>
      </FadeGroup>
    </section>
  );
}

function Lightbox({ index, setIndex }) {
  const { t, p } = useLang();
  const photos = DS.photos;
  const close = () => setIndex(null);
  const step = (d) => setIndex((i) => (i + d + photos.length) % photos.length);
  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === "Escape") close();
      if (e.key === "ArrowLeft") step(-1);
      if (e.key === "ArrowRight") step(1);
    };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { window.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, []);
  if (index == null) return null;
  const ph = photos[index];
  const tour = DS.tours.find((x) => x.id === ph.tour);
  return (
    <div className="lightbox" role="dialog" aria-modal="true" aria-label={t("photo_viewer")} onClick={(e) => { if (e.target === e.currentTarget) close(); }}>
      <button className="lightbox-close" aria-label={t("close")} onClick={close}><IconX /></button>
      <button className="lightbox-nav prev" aria-label={t("photo_prev")} onClick={() => step(-1)}><IconChevron dir="left" /></button>
      <img src={ph.src} alt={p(ph.alt)} />
      <p className="lightbox-caption">{p(ph.alt)}{tour ? " — " + p(tour.name) : ""}</p>
      <button className="lightbox-nav next" aria-label={t("photo_next")} onClick={() => step(1)}><IconChevron /></button>
    </div>
  );
}

/* ---------- reviews ---------- */
function ReviewsSection() {
  const { t, p } = useLang();
  const b = DS.brand;
  const total = Object.values(b.ratingBreakdown).reduce((a, n) => a + n, 0);
  return (
    <div className="section-band">
      <section className="section" id="reviews" data-screen-label="Reviews">
        <FadeGroup>
          <div className="section-head">
            <p className="eyebrow">{t("reviews_eyebrow")}</p>
            <h2>{t("reviews_title")}</h2>
          </div>
          <div className="reviews-layout">
            <aside className="rating-summary">
              <span className="rating-big">{b.rating.toFixed(1)}</span>
              <Stars rating={b.rating} className="rating-stars" />
              <span className="rating-count">{t("reviews_verified", { n: b.reviewCount })}</span>
              <div className="bars">
                {[5, 4, 3, 2, 1].map((star) => {
                  const n = b.ratingBreakdown[star] || 0;
                  return (
                    <div className="bar-row" key={star}>
                      <span>{star}★</span>
                      <span className="bar-track"><span className="bar-fill" style={{ width: (total ? (n / total) * 100 : 0) + "%" }}></span></span>
                      <span>{n}</span>
                    </div>
                  );
                })}
              </div>
            </aside>
            <div className="review-list">
              {DS.reviews.map((r) => {
                const tour = DS.tours.find((x) => x.id === r.tourId);
                return (
                  <article className="review-card" key={r.id}>
                    <div className="review-head">
                      <span className="review-author">{r.author}</span>
                      <span className="review-origin">{p(r.origin)}</span>
                      <span className="review-date">{p(r.date)}</span>
                    </div>
                    <Stars rating={r.rating} className="review-stars" />
                    <p className="review-text">{p(r.text)}</p>
                    {tour ? <span className="review-tour">{p(tour.name)}</span> : null}
                  </article>
                );
              })}
            </div>
          </div>
        </FadeGroup>
      </section>
    </div>
  );
}

/* ---------- about ---------- */
function AboutSection() {
  const { t, p } = useLang();
  const b = DS.brand;
  return (
    <section className="section" id="about" data-screen-label="About the guide">
      <FadeGroup>
        <div className="about-layout">
          <figure className="about-photo">
            <img src="images/guide-summit.jpg" alt={t("about_figcaption")} />
            <figcaption>{t("about_figcaption")}</figcaption>
          </figure>
          <div className="about-content">
            <p className="eyebrow">{t("about_eyebrow")}</p>
            <h2>{t("about_title1")}<br />{t("about_title2")}</h2>
            <p>{t("about_p1", { years: b.experienceYears })}</p>
            <p>{t("about_p2")}</p>
            <div className="cred-grid">
              <div className="cred"><b>{t("cred_years", { n: b.experienceYears })}</b><span>{t("cred_experience")}</span></div>
              <div className="cred"><b>{b.rating.toFixed(1)} / 5</b><span>{t("cred_reviews", { n: b.reviewCount })}</span></div>
              <div className="cred"><b>{t("cred_langs", { n: b.languages.length })}</b><span>{p(b.languagesDisplay)}</span></div>
              <div className="cred"><b>{t("cred_location")}</b><span>{t("cred_based")}</span></div>
            </div>
            <ul className="cred-list">
              {b.certifications.map((c, i) => <li key={i}>{p(c)}</li>)}
            </ul>
          </div>
        </div>
      </FadeGroup>
    </section>
  );
}

/* ---------- reservation ---------- */
function ReserveSection({ preselect }) {
  const { t, p } = useLang();
  const [values, setValues] = React.useState({
    name: "", phone: "", email: "", tour: preselect || "", date: "", size: "2", message: ""
  });
  const [errors, setErrors] = React.useState({});
  const [sent, setSent] = React.useState(null);

  React.useEffect(() => {
    if (preselect) setValues((v) => ({ ...v, tour: preselect }));
  }, [preselect]);

  const set = (k) => (e) => setValues((v) => ({ ...v, [k]: e.target.value }));

  const tourName = (id) => {
    if (id === "unsure") return t("unsure");
    const tour = DS.tours.find((x) => x.id === id);
    return tour ? p(tour.name) : id;
  };

  // Build the pre-filled WhatsApp message (the booking request itself).
  const bookingMessage = (v) => t("wa_booking_text", {
    name: v.name,
    phone: v.phone,
    email: v.email || "—",
    tour: tourName(v.tour),
    date: v.date,
    size: v.size,
    message: v.message || "—"
  });

  const submit = (e) => {
    e.preventDefault();
    const errs = {};
    if (!values.name.trim()) errs.name = t("err_name");
    if (!values.phone.trim()) errs.phone = t("err_phone");
    if (!values.tour) errs.tour = t("err_tour");
    if (!values.date) errs.date = t("err_date");
    setErrors(errs);
    if (Object.keys(errs).length > 0) return;

    // Zero-setup delivery: open WhatsApp to Hamza pre-filled with the request.
    window.open(WA_LINK + "?text=" + encodeURIComponent(bookingMessage(values)), "_blank", "noopener");
    setSent({ ...values });
  };

  return (
    <div className="section-band">
      <section className="section" id="reserve" data-screen-label="Reservation">
        <FadeGroup>
          <div className="section-head">
            <p className="eyebrow">{t("reserve_eyebrow")}</p>
            <h2>{t("reserve_title")}</h2>
            <p className="sub">{t("reserve_sub")}</p>
          </div>
          <div className="reserve-layout">
            <aside className="reserve-aside">
              <p>{t("reserve_aside")}</p>
              <div className="reserve-direct">
                <a href={WA_LINK} target="_blank" rel="noopener"><IconWhatsApp /> {t("reserve_wa", { n: DS.brand.whatsappDisplay })}</a>
                <a href={TEL_LINK}><IconPhone /> {t("reserve_call", { n: DS.brand.whatsappDisplay })}</a>
              </div>
            </aside>

            {sent ? (
              <div className="confirm" data-screen-label="Reservation confirmation">
                <p className="eyebrow">{t("confirm_eyebrow")}</p>
                <h3>{t("confirm_title", { name: sent.name.split(" ")[0] })}</h3>
                <p>{t("confirm_body1")}<strong>{t("confirm_body_strong")}</strong>{t("confirm_body2")}</p>
                <div className="confirm-summary">
                  <span><b>{t("label_tour")}</b> — {tourName(sent.tour)}</span>
                  <span><b>{t("label_date")}</b> — {sent.date}</span>
                  <span><b>{t("label_group")}</b> — {sent.size} {Number(sent.size) === 1 ? t("person") : t("people")}</span>
                  <span><b>{t("label_whatsapp")}</b> — {sent.phone}</span>
                </div>
                <div style={{ display: "flex", flexWrap: "wrap", gap: "12px" }}>
                  <a className="btn btn-solid" href={WA_LINK + "?text=" + encodeURIComponent(bookingMessage(sent))} target="_blank" rel="noopener">{t("open_wa_now")}</a>
                  <button className="btn btn-outline" onClick={() => setSent(null)}>{t("edit_request")}</button>
                </div>
              </div>
            ) : (
              <form className="reserve-form" onSubmit={submit} noValidate>
                <div className={"field" + (errors.name ? " invalid" : "")}>
                  <label htmlFor="f-name">{t("f_name")}</label>
                  <input id="f-name" type="text" value={values.name} onChange={set("name")} autoComplete="name" />
                  {errors.name ? <span className="err">{errors.name}</span> : null}
                </div>
                <div className={"field" + (errors.phone ? " invalid" : "")}>
                  <label htmlFor="f-phone">{t("f_phone")}</label>
                  <input id="f-phone" type="tel" value={values.phone} onChange={set("phone")} placeholder={t("f_phone_ph")} autoComplete="tel" />
                  {errors.phone ? <span className="err">{errors.phone}</span> : null}
                </div>
                <div className="field">
                  <label htmlFor="f-email">{t("f_email")} <span style={{ opacity: 0.6 }}>{t("optional")}</span></label>
                  <input id="f-email" type="email" value={values.email} onChange={set("email")} autoComplete="email" />
                </div>
                <div className={"field" + (errors.tour ? " invalid" : "")}>
                  <label htmlFor="f-tour">{t("f_tour")}</label>
                  <select id="f-tour" value={values.tour} onChange={set("tour")}>
                    <option value="">{t("choose_tour")}</option>
                    {DS.tours.map((tour) => <option key={tour.id} value={tour.id}>{p(tour.name)} — {p(tour.duration)}</option>)}
                    <option value="unsure">{t("unsure")}</option>
                  </select>
                  {errors.tour ? <span className="err">{errors.tour}</span> : null}
                </div>
                <div className={"field" + (errors.date ? " invalid" : "")}>
                  <label htmlFor="f-date">{t("f_date")}</label>
                  <input id="f-date" type="date" value={values.date} onChange={set("date")} />
                  {errors.date ? <span className="err">{errors.date}</span> : null}
                </div>
                <div className="field">
                  <label htmlFor="f-size">{t("f_size")}</label>
                  <select id="f-size" value={values.size} onChange={set("size")}>
                    {[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].map((n) => <option key={n} value={n}>{n}</option>)}
                  </select>
                </div>
                <div className="field full">
                  <label htmlFor="f-msg">{t("f_message")} <span style={{ opacity: 0.6 }}>{t("optional")}</span></label>
                  <textarea id="f-msg" value={values.message} onChange={set("message")} placeholder={t("f_message_ph")}></textarea>
                </div>
                <div className="form-foot">
                  <button type="submit" className="btn btn-solid">{t("send_request")}</button>
                  <span className="form-note">{t("form_note")}</span>
                </div>
              </form>
            )}
          </div>
        </FadeGroup>
      </section>
    </div>
  );
}

/* ---------- footer + fixed contact ---------- */
function SiteFooter() {
  const { t } = useLang();
  return (
    <footer className="site-footer">
      <div className="footer-inner">
        <a className="wordmark" href="#top" style={{ color: "inherit" }}>
          <span className="wm-top">Imlil Trips</span>
          <span className="wm-sub">{t("wm_sub")}</span>
        </a>
        <nav className="footer-nav" aria-label="Footer">
          <a href="#tours">{t("nav_tours")}</a>
          <a href="#photos">{t("nav_photos")}</a>
          <a href="#reviews">{t("nav_reviews")}</a>
          <a href="#about">{t("nav_about")}</a>
          <a href="#reserve">{t("nav_reserve")}</a>
        </nav>
        <p className="fine">{t("footer_fine")} · {DS.brand.whatsappDisplay} · <a href={"mailto:" + DS.brand.email} style={{ color: "inherit" }}>{DS.brand.email}</a></p>
      </div>
      <div className="footer-legal">
        <span>{t("footer_rights", { year: new Date().getFullYear() })}</span>
        <span className="footer-credit">{t("footer_credit")} <a href="https://vctrum.ca" target="_blank" rel="noopener">vctrum.ca</a></span>
      </div>
    </footer>
  );
}

function FixedContact() {
  const { t } = useLang();
  return (
    <div className="fixed-contact">
      <a className="wa" href={WA_LINK} target="_blank" rel="noopener" aria-label={t("msg_whatsapp")}><IconWhatsApp size={22} /></a>
      <a href={TEL_LINK} aria-label={t("call_hamza")}><IconPhone size={20} /></a>
    </div>
  );
}

Object.assign(window, {
  GallerySection, Lightbox, ReviewsSection, AboutSection, ReserveSection, SiteFooter, FixedContact
});
