/* Shared components + data for Paria Outpost */

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "light",
  "density": "regular"
}/*EDITMODE-END*/;

const STORAGE_KEY = "paria_tweaks_v3";

function loadTweaks() {
  try {
    const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) || "null");
    return { ...TWEAK_DEFAULTS, ...(saved || {}) };
  } catch { return TWEAK_DEFAULTS; }
}

function applyTweaks(t) {
  const root = document.documentElement;
  root.dataset.theme = t.theme;
  root.dataset.density = t.density;
}

/* ──────────────────────────────────────────────────────────
   TOUR DATA — sourced from paria.com
────────────────────────────────────────────────────────── */
const TOURS = [
  {
    slug: "soap-creek",
    num: "01",
    region: "no-permit",
    regionName: "Vermilion Cliffs NM",
    title: "Soap Creek",
    short: "The most remote tour. Largely unvisited, through the heart of the Vermilion Cliffs.",
    long: "An all-day tour into the southwest side of the Vermilion Cliffs National Monument — the part almost nobody sees. A scenic drive through formation-rich Pinnacle Valley, a stop at the linear brain rocks of Joe's Ranch, a 1-mile-each-way hike to the \"Great Wall of Colors\" and a Grand Canyon view, and a hike through the main Soap Creek Amphitheater. We're the only company that runs this — it's too far from Page or Kanab for anyone else to reach.",
    duration: "8–9 hours",
    permit: "No permit required",
    photo: "photos/soap-creek.jpg",
    photoLabel: "SOAP CREEK · VERMILION CLIFFS"
  },
  {
    slug: "the-wave",
    num: "02",
    region: "permit",
    regionName: "Coyote Buttes North",
    title: "The Wave",
    short: "Permit-only sandstone basin. Lottery is competitive — we'll help you try.",
    long: "A 6-mile round-trip hike across Navajo Sandstone to the striped hollow on every desert-photography poster. Requires a BLM permit, issued through an advance online lottery (four months ahead) and a next-day in-person geographic lottery. We cannot obtain the permit for you, but we help you understand the process, and guide your day once you have one.",
    duration: "8–9 hours",
    permit: "BLM permit required (lottery)",
    photo: "photos/the-wave.jpg",
    photoLabel: "THE WAVE · COYOTE BUTTES NORTH"
  },
  {
    slug: "south-coyote-buttes",
    num: "03",
    region: "permit",
    regionName: "Coyote Buttes South",
    title: "South Coyote Buttes",
    short: "Cottonwood Cove and Paw Hole. The Wave's quieter, stranger sibling.",
    long: "The less-contested permit-controlled half of Coyote Buttes. We guide in to Cottonwood Cove — up to five or six miles of hiking to reach the best striped teepees and slickrock — and to Paw Hole, which is not to be underrated. Four-wheel-drive access from House Rock Valley Road. Permits still need to be won, but the odds are better than The Wave.",
    duration: "8–9 hours",
    permit: "BLM permit required",
    photo: "photos/south-coyote-buttes.jpg",
    photoLabel: "COTTONWOOD COVE · CB SOUTH"
  },
  {
    slug: "white-pocket",
    num: "04",
    region: "no-permit",
    regionName: "Vermilion Cliffs NM",
    title: "White Pocket",
    short: "Cauliflower and brain-rock sandstone. No permit, but 4WD-only deep sand.",
    long: "A remote pocket of pink and butterscotch cauliflower sandstone and brain rocks, without the permit pressure of Coyote Buttes. Access is 4WD-only across deep sand on the Paria Plateau — almost everyone who tries to reach it without a local gets stuck. We also run a White Pocket Further tour, which adds the extended sandstone field beyond the main pocket.",
    duration: "8–9 hours",
    permit: "No permit required",
    photo: "photos/white-pocket.jpg",
    photoLabel: "WHITE POCKET · VERMILION CLIFFS"
  },
  {
    slug: "yellow-rock",
    num: "05",
    region: "no-permit",
    regionName: "Grand Staircase-Escalante",
    title: "Yellow Rock",
    short: "A giant dome of bright swirling color. Thirty-minute climb, world-class views.",
    long: "Twenty miles down Cottonwood Canyon Road — one of the most scenic roads in Southern Utah — is a dome of brightly swirled sandstone known in the landscape-photography world and largely unvisited by everyone else. A somewhat steep 30-minute climb gets you on top. Stunning views of the Cockscomb fault line, which the road follows for 48 miles, and a lot to explore in the surrounding Cockscomb area.",
    duration: "8–9 hours",
    permit: "No permit required",
    photo: "photos/yellow-rock.jpg",
    photoLabel: "YELLOW ROCK · COCKSCOMB"
  },
  {
    slug: "sidestep-canyon",
    num: "06",
    region: "no-permit",
    regionName: "Grand Staircase-Escalante",
    title: "Sidestep Canyon",
    short: "A valley full of balanced rocks — some three feet tall, some one hundred and fifty.",
    long: "Only half an hour from the Outpost — a two-and-a-half-mile march out, and then you're in an expansive green, white, and red valley full of balanced rocks. Literally hundreds of them, from three feet to a hundred and fifty feet tall — possibly the tallest balanced rock in the state. We can go all the way through to the bottom of Wahweap Wash and into the canyon on the other side. Never crowded. Bizarre geology in every direction.",
    duration: "8–9 hours",
    permit: "No permit required",
    photo: "photos/sidestep-canyon.jpg",
    photoLabel: "SIDESTEP CANYON · BALANCED ROCKS"
  },
  {
    slug: "vermilion-cliffs",
    num: "07",
    region: "no-permit",
    regionName: "Vermilion Cliffs NM",
    title: "Vermilion Cliffs",
    short: "The whole plateau by Suburban. The tour only we offer.",
    long: "A wide-ranging scenic drive across the 500-square-mile Paria Plateau — the \"Sand Hills\" of pioneer days, now the Vermilion Cliffs National Monument. Pinnacle Valley, the orange-and-white brain rocks of the Middle Reservoir, Double Barrel Arch, the Brain Rocks of Joe's Ranch, and the colors of Soap Creek, with stops for Anasazi petroglyphs and habitation sites. Because of our proximity we're the only operator who runs this. Fully customizable to your interests and hiking ability.",
    duration: "8–9 hours",
    permit: "No permit required",
    photo: "photos/vermilion-cliffs.jpg",
    photoLabel: "VERMILION CLIFFS · PARIA PLATEAU"
  },
  {
    slug: "grand-staircase",
    num: "08",
    region: "no-permit",
    regionName: "Grand Staircase-Escalante",
    title: "Grand Staircase",
    short: "A million-plus acres. Three scenic roads, each entirely its own landscape.",
    long: "The Southern Grand Staircase-Escalante and the BLM land around it — over a million acres of canyons, badlands, hoodoos, balanced rocks, and brightly colored formations. We can show you the Rimrocks hoodoos, the highlights of the Paria River Area, or hike Buckskin Gulch or Wire Pass. Three main scenic roads leave from minutes away: Cottonwood Canyon Road (48 miles following a tectonic fault), Smoky Mountain Road (4WD, high viewpoints, underground coal fires), and Johnson Canyon Road — each its own day.",
    duration: "8–9 hours",
    permit: "No permit required",
    photo: "photos/grand-staircase.jpg",
    photoLabel: "GRAND STAIRCASE · RIMROCKS"
  },
  {
    slug: "overnight",
    num: "09",
    region: "overnight",
    regionName: "Overnight camp",
    title: "Overnight Tours",
    short: "Noon-to-noon overnights for sunset, the Milky Way, and sunrise.",
    long: "Our overnight camp-outs run 24 hours, usually noon to noon. Sunset, the stars, sunrise — the two windows of best light around a night under the desert sky. We provide tents, sleeping bags, pads, a table and chairs — or bring your own. A sack lunch, dinner, breakfast, water and cold drinks are all included. These are primitive camping experiences, not glamping. Our guides will help you capture that special light and find the right location.",
    duration: "24 hours · noon to noon",
    permit: "No permit required",
    photo: "photos/overnight.jpg",
    photoLabel: "MILKY WAY · OVERNIGHT TOUR"
  }
];

const REGIONS = [
  { slug: "permit",    name: "Permit-required day tours", sub: "BLM permit · Coyote Buttes" },
  { slug: "no-permit", name: "No-permit day tours",       sub: "No lottery required · Same price" },
  { slug: "overnight", name: "Overnight camp-outs",       sub: "Noon to noon · Under the stars" },
];

/* ──────────────────────────────────────────────────────────
   SMART IMAGE — falls back to striped placeholder if missing
────────────────────────────────────────────────────────── */
function SmartImg({ src, label, tone = "sand", alt }) {
  const [ok, setOk] = React.useState(!!src);
  React.useEffect(() => {
    if (!src) { setOk(false); return; }
    const img = new Image();
    img.onload = () => setOk(true);
    img.onerror = () => setOk(false);
    img.src = src;
  }, [src]);

  if (ok && src) {
    return (
      <div className="img-wrap">
        <img className="img" src={src} alt={alt || label} loading="lazy" />
      </div>
    );
  }
  return <div className={`img-ph ${tone}`} data-label={label} role="img" aria-label={alt || label} />;
}

/* ──────────────────────────────────────────────────────────
   NAV
────────────────────────────────────────────────────────── */
function Nav({ active = "home" }) {
  const [open, setOpen] = React.useState(false);
  React.useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);
  const close = () => setOpen(false);
  return (
    <nav className={`nav ${open ? "open" : ""}`}>
      <div className="nav-inner">
        <a href="index.html" className="nav-logo">
          <span className="brand">Paria&nbsp;<em>Outpost</em></span>
          <small>EST · 1998</small>
        </a>
        <div className="nav-links">
          <a href="index.html" onClick={close} className={active==="home"?"active":""}>Home</a>
          <a href="tours.html" onClick={close} className={active==="tours"?"active":""}>Tours</a>
          <a href="workshops.html" onClick={close} className={active==="workshops"?"active":""}>Workshops</a>
          <a href="photos.html" onClick={close} className={active==="photos"?"active":""}>Photos</a>
          <a href="about.html" onClick={close} className={active==="about"?"active":""}>About</a>
        </div>
        <div className="nav-right">
          <a href="https://www.facebook.com/Paria-Outpost-Outfitters-202261523247333/" target="_blank" rel="noopener" className="nav-social" aria-label="Facebook">
            <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor" aria-hidden="true"><path d="M13.5 21v-8h2.7l.4-3.2H13.5V7.8c0-.9.3-1.6 1.6-1.6h1.7V3.3c-.3 0-1.3-.1-2.4-.1-2.4 0-4 1.5-4 4.1v2.5H7.7V13h2.7v8h3.1z"/></svg>
          </a>
          <a href="https://www.instagram.com/pariaoutpostadventures/" target="_blank" rel="noopener" className="nav-social" aria-label="Instagram">
            <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.8" 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>
          </a>
          <a href="about.html#contact" className="nav-cta">Call us</a>
          <button
            type="button"
            className="nav-burger"
            aria-label={open ? "Close menu" : "Open menu"}
            aria-expanded={open}
            onClick={() => setOpen(v => !v)}
          >
            <span /><span /><span />
          </button>
        </div>
      </div>
    </nav>
  );
}

/* ──────────────────────────────────────────────────────────
   FOOTER
────────────────────────────────────────────────────────── */
function Footer() {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <div className="footer-brand">Paria <em>Outpost</em></div>
            <p className="footer-tagline">Guided photography &amp; hiking tours in the Vermilion Cliffs and Grand Staircase since 1998.</p>
            <div className="footer-contact">
              <div>Hwy 89 · Mile Marker 21.5</div>
              <div>PO Box 410075 · Big Water, UT 84741</div>
              <div><a href="tel:+19286911047">(928) 691-1047</a></div>
              <div><a href="mailto:outpost@paria.com">outpost@paria.com</a></div>
            </div>
            <div className="footer-social">
              <a href="https://www.facebook.com/Paria-Outpost-Outfitters-202261523247333/" target="_blank" rel="noopener">Facebook</a>
              <a href="https://www.instagram.com/pariaoutpostadventures/" target="_blank" rel="noopener">Instagram</a>
            </div>
          </div>
          <div>
            <h5>Tours</h5>
            <ul>
              {TOURS.map(t => <li key={t.slug}><a href={`tours.html#${t.slug}`}>{t.title}</a></li>)}
            </ul>
          </div>
          <div>
            <h5>Visit</h5>
            <ul>
              <li><a href="about.html">About the outpost</a></li>
              <li><a href="about.html#guides">Steve &amp; Susan</a></li>
              <li><a href="workshops.html">Photo workshops</a></li>
              <li><a href="photos.html">Photo galleries</a></li>
              <li><a href="tours.html#lodging">B&amp;B · Camping</a></li>
              <li><a href="tours.html#pricing">Pricing &amp; FAQ</a></li>
              <li><a href="about.html#for-sale">Property for sale</a></li>
            </ul>
          </div>
          <div>
            <h5>How we run</h5>
            <ul>
              <li>Tours 8–9 hours</li>
              <li>Cash or check only · No deposits</li>
              <li>Reschedule free for weather</li>
              <li>Permits for Wave &amp; S. Coyote Buttes only</li>
              <li>Kids 18 &amp; under $100 with 2 adults</li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <div>© 1998–2026 Paria Outpost &amp; Outfitters · Steve &amp; Susan Dodson</div>
          <div>Kane County, UT · Hwy 89 · Paria River bridge</div>
        </div>
      </div>
    </footer>
  );
}

/* ──────────────────────────────────────────────────────────
   TWEAKS
────────────────────────────────────────────────────────── */
function Tweaks() {
  const [t, setT] = React.useState(loadTweaks);
  const [open, setOpen] = React.useState(false);

  React.useEffect(() => {
    applyTweaks(t);
    localStorage.setItem(STORAGE_KEY, JSON.stringify(t));
    try {
      window.parent.postMessage({ type: "__edit_mode_set_keys", edits: t }, "*");
    } catch {}
  }, [t]);

  React.useEffect(() => {
    const listener = (e) => {
      if (!e.data || typeof e.data !== "object") return;
      if (e.data.type === "__activate_edit_mode") setOpen(true);
      if (e.data.type === "__deactivate_edit_mode") setOpen(false);
    };
    window.addEventListener("message", listener);
    try { window.parent.postMessage({ type: "__edit_mode_available" }, "*"); } catch {}
    return () => window.removeEventListener("message", listener);
  }, []);

  const Seg = ({ k, opts, two }) => (
    <div className={`tweaks-seg ${two ? "two" : ""}`}>
      {opts.map(o => (
        <button
          key={o.v}
          className={t[k]===o.v?"on":""}
          onClick={()=>setT({...t,[k]:o.v})}
        >{o.label}</button>
      ))}
    </div>
  );

  return (
    <div className={`tweaks ${open ? "open" : ""}`}>
      <h4>Tweaks</h4>
      <div className="tweaks-row">
        <label>Theme</label>
        <Seg k="theme" two opts={[{v:"light",label:"Light"},{v:"dark",label:"Dark"}]} />
      </div>
      <div className="tweaks-row">
        <label>Density</label>
        <Seg k="density" opts={[{v:"compact",label:"Compact"},{v:"regular",label:"Regular"},{v:"airy",label:"Airy"}]} />
      </div>
      <p className="tweaks-note">Photos sourced from paria.com. Drop new JPGs into <code>photos/</code> to swap.</p>
    </div>
  );
}

/* ──────────────────────────────────────────────────────────
   TRIPADVISOR WIDGET — same location id (1903239) as paria.com
────────────────────────────────────────────────────────── */
function TripAdvisor() {
  React.useEffect(() => {
    // The widget registers a validator on window.taValidate (which runs on window.onload).
    // React mounts after onload has fired, so we poll briefly and fire taValidate() manually.
    const s = document.createElement("script");
    s.async = true;
    s.src = "https://www.jscache.com/wejs?wtype=selfserveprop&uniq=502&locationId=1903239&lang=en_US&rating=true&nreviews=5&writereviewlink=true&popIdx=true&iswide=true&border=false&display_version=2";
    document.body.appendChild(s);
    let tries = 0;
    const poll = setInterval(() => {
      tries++;
      if (typeof window.taValidate === "function") {
        try { window.taValidate(); } catch {}
        clearInterval(poll);
      } else if (tries > 40) {
        clearInterval(poll);
      }
    }, 250);
    return () => { clearInterval(poll); try { document.body.removeChild(s); } catch {} };
  }, []);
  return (
    <section className="tripadvisor">
      <div className="container">
        <div className="pricing-head">
          <div className="k">Reviews</div>
          <h2>What our guests say on TripAdvisor.</h2>
        </div>
        <div id="TA_selfserveprop502" className="TA_selfserveprop">
          <ul id="paria-ta-links" className="TA_links">
            <li>
              <a target="_blank" rel="noopener" href="https://www.tripadvisor.com/Attraction_Review-g60779-d1903239">
                <img src="https://www.tripadvisor.com/img/cdsi/img2/branding/150_logo-11900-2.png" alt="TripAdvisor" />
              </a>
            </li>
          </ul>
        </div>
      </div>
    </section>
  );
}

/* Apply stored tweaks on first paint so nav etc. don't flash */
applyTweaks(loadTweaks());

/* Export globals */
Object.assign(window, { Nav, Footer, Tweaks, SmartImg, TripAdvisor, TOURS, REGIONS });
