/* SAFRI — main app. All text/links read from window.SAFRI_DATA (injected by WordPress). */
const { useState: useS, useEffect: useE, useRef: useR } = React;

// Shorthand accessors
const _D = window.SAFRI_DATA || {};
const _S = _D.sections       || {};
const _H = _D.hero            || {};
const _N = _D.nav             || {};
const _F = _D.footer          || {};

// Logo: read data-src from the PHP-rendered hidden img (exact string, no browser URL resolution).
// Falls back to SAFRI_DATA.logoUrl which is always an absolute URL from PHP.
const LOGO_URL = (() => {
  const el = document.getElementById('safri-logo-el');
  if (el && el.dataset && el.dataset.src) return el.dataset.src;
  return _D.logoUrl || '';
})();

/* ---------- Nav ---------- */
function Nav(){
  const [open, setOpen] = useS(false);
  const close = () => setOpen(false);
  const links  = _D.menu || [
    { label:"Tours",      href:"#tours"   },
    { label:"Rent a Car", href:"#rent"    },
    { label:"Umrah",      href:"#umrah"   },
    { label:"Reviews",    href:"#reviews" },
    { label:"Contact",    href:"#contact" },
  ];
  const ctaText = _N.ctaText || "Plan my trip";

  return (
    <nav className={"nav" + (open ? " open" : "")}>
      <a href="#top" className="nav-brand" onClick={close}>
        <img className="nav-logo" src={LOGO_URL} alt="Safri Travels &amp; Tours"/>
      </a>
      <div className="nav-links">
        {links.map((l, i) => <a key={i} href={l.href} onClick={close}>{l.label}</a>)}
      </div>
      <a className="nav-cta"
         href={waLink("As-salam alaikum Safri Travels 👋 I'd like to plan a trip.")}
         target="_blank" rel="noreferrer">
        <Icons.wa size={16}/> {ctaText}
      </a>
      <button className="nav-burger" onClick={() => setOpen(o => !o)} aria-label="menu">
        <span></span><span></span><span></span>
      </button>
    </nav>
  );
}

/* ---------- Hero ---------- */
function Hero(){
  const eyebrow  = _H.eyebrow  || "Lahore-based · serving all of Pakistan · since 2018";
  const line1    = _H.line1    || "From Safri";
  const line2    = _H.line2    || "to Sukoon.";
  const sub      = _H.sub      || "A Lahore travel agency turning Pakistan's northern peaks and Islam's holiest cities into seamless, worry-free journeys.";
  const btn1Text = _H.btn1Text || "Start the journey";
  const btn1Href = _H.btn1Href || "#tours";
  const btn2Text = _H.btn2Text || "Talk to a human";

  return (
    <section className="hero wrap" id="top" data-screen-label="Hero">
      <div className="hero-grid">
        <div>
          <span className="eyebrow reveal">{eyebrow}</span>
          <h1 className="reveal">
            <span className="line">{line1.replace(/ (\S+)$/, " ")}<span className="grad-orange">{line1.trim().split(" ").pop()}</span></span>
            <span className="line">{line2.split(" ")[0]} <span className="grad-ink">{line2.split(" ").slice(1).join(" ")}</span></span>
          </h1>
          <p className="hero-sub muted reveal">{sub}</p>
          <div className="hero-actions reveal">
            <a className="btn btn-primary" href={btn1Href}>
              <Icons.compass size={18} color="#fff"/> {btn1Text}
            </a>
            <a className="btn btn-ghost"
               href={waLink("As-salam alaikum Safri Travels 👋 I'd like to talk to a consultant.")}
               target="_blank" rel="noreferrer">
              <Icons.wa size={18}/> {btn2Text}
            </a>
          </div>
          <div className="hero-stats reveal">
            {STATS.slice(0, 3).map((s, i) => (
              <div className="stat" key={i}><b className="grad-orange">{s.n}</b><span>{s.l}</span></div>
            ))}
          </div>
        </div>
        <BookingWidget/>
      </div>
      <a href="#tours" className="scroll-hint reveal" aria-label="scroll">
        <span>Scroll the story</span>
        <span className="sh-mouse"><span></span></span>
      </a>
    </section>
  );
}

/* ---------- Section header ---------- */
function Head({ eyebrow, title, sub, id, center }){
  return (
    <div className={"sec-head reveal" + (center ? " center" : "")} id={id}>
      <span className="eyebrow">{eyebrow}</span>
      <h2>{title}</h2>
      {sub && <p className="muted">{sub}</p>}
    </div>
  );
}

/* ---------- Tours ---------- */
function Tours(){
  const sc = _S.tours || {};
  return (
    <section className="section-pad wrap" id="tours" data-screen-label="Tours">
      <Head
        eyebrow={sc.eyebrow || "Domestic Tours · the mountains"}
        title={<>{(sc.heading || "The north, refined year after year.").replace(/, refined.*/, "")}, <span className="grad-ink">refined year after year.</span></>}
        sub={sc.sub}
      />
      <div className="tour-grid">
        {TOURS.map((t, i) => (
          <a key={i} className="tour reveal"
             href={waLink(`As-salam alaikum Safri Travels 👋 I'd like the itinerary & package for the *${t.name}* tour (${t.days}).`)}
             target="_blank" rel="noreferrer">
            <span className="tdot" style={{ background: t.color + "1f" }}><Icons.mountain size={18} color={t.color}/></span>
            <h4>{t.name}</h4>
            <div className="tmeta">{t.days} · group or private</div>
            <span className="tlink">See itinerary <Icons.arrow size={15}/></span>
          </a>
        ))}
      </div>
    </section>
  );
}

/* ---------- Rent a Car ---------- */
function Rent(){
  const sc = _S.rent || {};
  return (
    <section className="section-pad wrap" id="rent" data-screen-label="Rent a Car">
      <div className="service reveal">
        <div className="service-media" style={{ background:"linear-gradient(140deg,rgba(240,72,0,.10),rgba(0,168,240,.08))" }}>
          <span className="service-num">01</span>
          <div className="media-headline grad-ink">{sc.mediaHeadline || "Mountain-graded fleet, driver included."}</div>
          <div className="media-badges">
            {VEHICLES.map((v, i) => (
              <span className="media-badge" key={i}><Icons.car size={15} color="#F04800"/> {v.name} · {v.seats} seats</span>
            ))}
          </div>
        </div>
        <div>
          <span className="service-tag grad-orange">{sc.tag || "Rent a Car"}</span>
          <h3>{sc.heading || "Sedans to Land Cruisers — no surprises."}</h3>
          <p className="muted">{sc.sub}</p>
          <ul className="feat-list">
            <li><Icons.shield size={18} color="#186060"/><span><b>{sc.feat1Title || "Background-checked drivers"}</b> {sc.feat1Desc}</span></li>
            <li><Icons.mountain size={18} color="#186060"/><span><b>{sc.feat2Title || "4×4s graded for the Karakoram"}</b> {sc.feat2Desc}</span></li>
            <li><Icons.check size={18} color="#186060"/><span><b>{sc.feat3Title || "All-in daily rate"}</b> {sc.feat3Desc}</span></li>
          </ul>
          <a className="btn btn-primary"
             href={waLink("As-salam alaikum Safri Travels 👋 I'd like to *RENT A CAR*. Please share availability & your best package.")}
             target="_blank" rel="noreferrer">
            <Icons.wa size={18} color="#fff"/> {sc.btnText || "Get a vehicle quote"}
          </a>
        </div>
      </div>
    </section>
  );
}

/* ---------- Custom tours ---------- */
function Custom(){
  const sc = _S.custom || {};
  return (
    <section className="section-pad wrap" data-screen-label="Custom Tours">
      <div className="service flip reveal">
        <div className="service-media" style={{ background:"linear-gradient(140deg,rgba(24,96,96,.10),rgba(240,72,0,.07))" }}>
          <span className="service-num">02</span>
          <div className="media-headline grad-orange">{sc.mediaHeadline || "A Hunza honeymoon. A family Umrah. A solo reset."}</div>
          <div className="media-badges">
            <span className="media-badge"><Icons.spark size={15} color="#186060"/> Tailored itinerary</span>
            <span className="media-badge"><Icons.clock size={15} color="#186060"/> Reply within 24h</span>
            <span className="media-badge"><Icons.check size={15} color="#186060"/> Free, no obligation</span>
          </div>
        </div>
        <div>
          <span className="service-tag" style={{ color:"#186060" }}>{sc.tag || "Custom Tours"}</span>
          <h3>{sc.heading || "Tell us the dream. We'll draft it."}</h3>
          <p className="muted">{sc.sub}</p>
          <ul className="feat-list">
            <li><Icons.users size={18} color="#F04800"/><span>{sc.feat1 || "Built around your group, pace and budget."}</span></li>
            <li><Icons.compass size={18} color="#F04800"/><span>{sc.feat2 || "Nine in-house consultants who know every route."}</span></li>
            <li><Icons.phone size={18} color="#F04800"/><span>{sc.feat3 || "One WhatsApp thread from first idea to safe return."}</span></li>
          </ul>
          <a className="btn btn-primary"
             href={waLink("As-salam alaikum Safri Travels 👋 I'd like a *CUSTOM TOUR*. Here's my brief:\n• Destination: \n• Dates: \n• Travellers: \n• Notes: ")}
             target="_blank" rel="noreferrer">
            <Icons.wa size={18} color="#fff"/> {sc.btnText || "Share my brief"}
          </a>
        </div>
      </div>
    </section>
  );
}

/* ---------- Umrah ---------- */
function Umrah(){
  const sc = _S.umrah || {};
  return (
    <section className="section-pad wrap" id="umrah" data-screen-label="Umrah">
      <Head
        eyebrow={sc.eyebrow || "Umrah Packages · 1447 H · the Haram"}
        title={<>Pilgrimage, <span className="grad-orange">{(sc.heading || "Pilgrimage, perfected.").split(",")[1]?.trim() || "perfected."}</span></>}
        sub={sc.sub}
      />
      <div className="cards">
        {UMRAH.map((p, i) => (
          <div className={"pkg reveal" + (p.feature ? " feature" : "")} key={i}>
            {p.feature && <span className="pkg-flag">Most chosen</span>}
            <h4>{p.name}</h4>
            <div className="ptier">{p.tier} · {p.nights} · all-inclusive</div>
            <ul>
              {p.pts.map((x, j) => (
                <li key={j}><Icons.check size={17} color="#F04800"/><span>{x}</span></li>
              ))}
            </ul>
            <a className={"btn " + (p.feature ? "btn-primary" : "btn-ghost")}
               href={waLink(`As-salam alaikum Safri Travels 👋 I'm interested in the *${p.name}* Umrah package (${p.tier}, ${p.nights}). Please share the next departure & package for 1447 H.`)}
               target="_blank" rel="noreferrer">
              <Icons.wa size={17}/> Enquire on WhatsApp
            </a>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ---------- Why + stats ---------- */
function Why(){
  const sc = _S.why || {};
  return (
    <section className="section-pad wrap" id="why" data-screen-label="Why Safri">
      <Head
        eyebrow={sc.eyebrow || "Why travellers choose us"}
        title={<>Trusted by <span className="grad-orange">{(sc.heading || "Trusted by 12,000+ travellers.").match(/[\d,+★]+/)?.[0] || "12,000+"}</span> travellers.</>}
        sub={sc.sub}
      />
      <div className="why-grid">
        {WHY.map((w, i) => {
          const Ic = Icons[w.icon] || Icons.star;
          return (
            <div className="why reveal" key={i}>
              <span className="wicon" style={{ background:"linear-gradient(135deg,rgba(240,72,0,.14),rgba(24,96,96,.12))" }}>
                <Ic size={22} color="#F04800"/>
              </span>
              <h4>{w.t}</h4>
              <p className="muted">{w.d}</p>
            </div>
          );
        })}
      </div>
      <div className="bigstats reveal">
        {STATS.map((s, i) => (
          <div className="bs" key={i}><b>{s.n}</b><span>{s.l}</span></div>
        ))}
      </div>
    </section>
  );
}

/* ---------- Reviews ---------- */
function Reviews(){
  const [i, setI]       = useS(0);
  const [paused, pause] = useS(false);
  const n = REVIEWS.length;
  const sc = _S.reviews || {};

  useE(() => {
    if (paused) return;
    const id = setInterval(() => setI(p => (p + 1) % n), 5200);
    return () => clearInterval(id);
  }, [paused, n]);

  const go = d => setI(p => (p + d + n) % n);
  return (
    <section className="section-pad wrap" id="reviews" data-screen-label="Reviews">
      <Head center
        eyebrow={sc.eyebrow || "4.9★ · 1,200+ Google reviews"}
        title={<>Real journeys, <span className="grad-ink">{(sc.heading || "Real journeys, real words.").split(", ")[1] || "real words."}</span></>}
      />
      <div className="rev-stage reveal" onMouseEnter={() => pause(true)} onMouseLeave={() => pause(false)}>
        <button className="rev-arrow left" onClick={() => go(-1)} aria-label="previous"><Icons.arrow size={20}/></button>
        <div className="rev-track" style={{ transform:`translateX(-${i * 100}%)` }}>
          {REVIEWS.map((r, k) => (
            <div className="rev-card" key={k}>
              <Icons.quote size={40} color="#F0480022"/>
              <div className="rev-stars">{Array.from({length:5}).map((_, s) => <Icons.star key={s} size={18} color="#F04800"/>)}</div>
              <p className="rev-text">{r.text}</p>
              <div className="rev-person">
                <span className="rev-av" style={{ background:r.color }}>{r.initials}</span>
                <div><b>{r.name}</b><span>{r.trip}</span></div>
              </div>
            </div>
          ))}
        </div>
        <button className="rev-arrow right" onClick={() => go(1)} aria-label="next"><Icons.arrow size={20}/></button>
      </div>
      <div className="rev-dots">
        {REVIEWS.map((_, k) => (
          <button key={k} className={"rev-dot" + (i === k ? " active" : "")} onClick={() => setI(k)} aria-label={"review " + (k + 1)}></button>
        ))}
      </div>
    </section>
  );
}

/* ---------- How it works ---------- */
function How(){
  const sc = _S.how || {};
  return (
    <section className="section-pad wrap" data-screen-label="How it works">
      <Head
        eyebrow={sc.eyebrow || "How it works"}
        title={<>Four steps to <span className="grad-ink">{(sc.heading || "Four steps to show up & travel.").split("to ")[1] || "show up & travel."}</span></>}
      />
      <div className="steps">
        {STEPS.map((s, i) => (
          <div className="step reveal" key={i}><h4>{s.t}</h4><p className="muted">{s.d}</p></div>
        ))}
      </div>
    </section>
  );
}

/* ---------- CTA band ---------- */
function CTABand(){
  const sc       = _S.cta    || {};
  const phoneHref = _D.phoneHref || "tel:+923391172374";
  return (
    <section className="wrap" style={{ paddingBottom:"40px" }} id="contact" data-screen-label="Contact">
      <div className="cta-band reveal">
        <div className="glow" style={{ width:300, height:300, background:"#fff", top:-120, right:-60 }}></div>
        <div className="glow" style={{ width:260, height:260, background:"#186060", bottom:-120, left:-40, opacity:.4 }}></div>
        <h2>{sc.heading || "Your next journey starts with a message."}</h2>
        <p>{sc.sub}</p>
        <div className="hero-actions" style={{ justifyContent:"center" }}>
          <a className="btn btn-wa"
             href={waLink("As-salam alaikum Safri Travels 👋 I'd like to plan a journey. Here's what I have in mind:")}
             target="_blank" rel="noreferrer">
            <Icons.wa size={18}/> {sc.btn1Text || "Message us on WhatsApp"}
          </a>
          <a className="btn btn-ghost" href={phoneHref}
             style={{ color:"#fff", borderColor:"rgba(255,255,255,.5)", background:"rgba(255,255,255,.12)" }}>
            <Icons.phone size={18} color="#fff"/> {sc.btn2Text || _D.phone || "+92 339 1172374"}
          </a>
        </div>
      </div>
    </section>
  );
}

/* ---------- Footer ---------- */
function Footer(){
  const year  = _D.year  || new Date().getFullYear();
  const email = _D.email || "contact@safritravels.com";
  const address = _D.address || "Cavalry Ground, near Iceland Khalid Masjid, Lahore 54000";
  const phone   = _D.phone   || "+92 339 117 2374";
  const phoneHref = _D.phoneHref || "tel:+923391172374";

  return (
    <footer className="footer wrap" data-screen-label="Footer">
      <div className="foot-grid">
        <div className="foot-brand">
          <img className="foot-logo" src={LOGO_URL} alt="Safri Travels &amp; Tours"/>
          <p className="muted" style={{ fontSize:".92rem", maxWidth:"32ch", marginTop:14 }}>{_F.tagline}</p>
          <div className="foot-badges" style={{ marginTop:18 }}>
            {[_F.badge1, _F.badge2, _F.badge3].filter(Boolean).map((b, i) => (
              <span key={i} className="foot-badge">{b}</span>
            ))}
          </div>
        </div>
        <div className="foot-col">
          <h5>Services</h5>
          <a href="#tours">Domestic Tours</a>
          <a href="#rent">Rent a Car</a>
          <a href="#umrah">Umrah Packages</a>
          <a href={waLink("As-salam alaikum Safri Travels 👋 I'd like a custom tour.")} target="_blank" rel="noreferrer">Custom Tours</a>
        </div>
        <div className="foot-col">
          <h5>Company</h5>
          <a href="#why">Why Safri</a>
          <a href="#reviews">Reviews</a>
          <a href={waLink("As-salam alaikum Safri Travels 👋")} target="_blank" rel="noreferrer">Contact</a>
        </div>
        <div className="foot-col foot-contact">
          <h5>Get in touch</h5>
          <div><Icons.pin size={17} color="#F04800"/><span>{address}</span></div>
          <div><Icons.phone size={17} color="#F04800"/><a href={phoneHref}>{phone}</a></div>
          <div><Icons.mail size={17} color="#F04800"/><a href={`mailto:${email}`}>{email}</a></div>
        </div>
      </div>
      <div className="foot-bottom">
        <span>© {year} Safri Travels &amp; Tours · Lahore. All rights reserved.</span>
        <span>{_F.taglineRight || "From Safri to Sukoon."}</span>
      </div>
    </footer>
  );
}

/* ---------- Story rail ---------- */
function StoryRail(){
  const beats = [["Drive","#top"],["Mountains","#tours"],["Road","#rent"],["Haram","#umrah"],["Home","#contact"]];
  const [active, setActive] = useS(0);
  useE(() => {
    const id = setInterval(() => { if (window.SafriBG) setActive(Math.round(window.SafriBG.progress)); }, 200);
    return () => clearInterval(id);
  }, []);
  return (
    <div className="story-rail">
      {beats.map(([l, h], i) => (
        <a key={i} href={h} className={"dot" + (active === i ? " active" : "")}><span>{l}</span></a>
      ))}
    </div>
  );
}

/* ---------- Decorative road car ---------- */
function RoadCar(){
  const carRef = useR(null);
  useE(() => {
    let raf, cur = 0;
    const tick = () => {
      const max    = document.documentElement.scrollHeight - window.innerHeight;
      const target = max > 0 ? Math.min(1, Math.max(0, window.scrollY / max)) : 0;
      cur += (target - cur) * 0.08;
      if (carRef.current) {
        const y    = 24 + cur * (window.innerHeight - 110);
        const tilt = Math.max(-12, Math.min(12, (target - cur) * 120));
        carRef.current.style.transform = `translateY(${y}px) rotate(${tilt}deg)`;
      }
      raf = requestAnimationFrame(tick);
    };
    tick();
    return () => cancelAnimationFrame(raf);
  }, []);
  return (
    <div className="roadcar" aria-hidden="true">
      <div className="roadcar-line"></div>
      <div className="roadcar-car" ref={carRef}>
        <svg width="30" height="46" viewBox="0 0 30 46" fill="none">
          <rect x="5" y="3" width="20" height="40" rx="9" fill="#F04800"/>
          <rect x="7.5" y="7" width="15" height="9" rx="4" fill="#FFE7D6"/>
          <rect x="7.5" y="27" width="15" height="9" rx="4" fill="#FFE7D6" opacity=".85"/>
          <rect x="2.5" y="9" width="3" height="8" rx="1.5" fill="#186060"/>
          <rect x="24.5" y="9" width="3" height="8" rx="1.5" fill="#186060"/>
          <rect x="2.5" y="29" width="3" height="8" rx="1.5" fill="#186060"/>
          <rect x="24.5" y="29" width="3" height="8" rx="1.5" fill="#186060"/>
          <circle cx="11" cy="42" r="1.4" fill="#00A8F0"/><circle cx="19" cy="42" r="1.4" fill="#00A8F0"/>
        </svg>
      </div>
    </div>
  );
}

/* ---------- App root ---------- */
function App(){
  return (
    <>
      <RoadCar/>
      <Nav/>
      <Hero/>
      <Tours/>
      <Rent/>
      <Custom/>
      <Umrah/>
      <Why/>
      <Reviews/>
      <How/>
      <CTABand/>
      <Footer/>
      <StoryRail/>
      <a className="wa-float"
         href={waLink("As-salam alaikum Safri Travels 👋")}
         target="_blank" rel="noreferrer" aria-label="WhatsApp">
        <Icons.wa size={28} color="#fff"/>
      </a>
    </>
  );
}

ReactDOM.createRoot(document.getElementById("app")).render(<App/>);
