/* IJWestern — shared page shell.
   Globals: TopBar, Footer

   Extracted in step 4b. These two components were defined three times
   over — once each in app.jsx, west-mount.jsx and project.jsx — so a nav
   or contact change had to be made in three places and inevitably drifted.

   One `home` flag covers the only real difference between the two
   contexts: the home page navigates by in-page anchor, every other page
   has to prefix those anchors with index.html. Pass `onSchedule` when the
   host page wants the button to run a handler (the home page smooth-
   scrolls to its form); omit it and the button becomes a plain link. */

const IJW_CONTACT = {
  phone:     "+91 91485 21696",
  phoneHref: "tel:+919148521696",
  whatsapp:  "https://wa.me/919148521696",
  instagram: "https://www.instagram.com/ijwestern_realtors",
  email:     "visits@ijwestern.com",
  address1:  "9A, BLM Towers",
  address2:  "West Yakkara, Palakkad 678001",
  hours:     "09:00–21:00",
  coords:    "10.7867° N · 76.6557° E",
};

function ScheduleButton({ onSchedule, href, className = "btn btn-primary btn-glass btn-compact" }) {
  const inner = (
    <>
      <span className="cta-label"><span>Schedule a visit</span></span>
      <span className="arrow"><ArrowIcon /></span>
    </>
  );
  return onSchedule
    ? <button onClick={onSchedule} className={className}>{inner}</button>
    : <a href={href} className={className}>{inner}</a>;
}

/* `page` names which nav link is the current one on a page that is not
   the home page. It defaults to "projects", which is what every caller
   before step 8 relied on: the projects index and the five project
   pages all light Projects. about.html passes "about" and, from step 9,
   contact.html passes "contact". */
function TopBar({ home = false, page = "projects", activeSection = null, onSchedule = null }) {
  const [onDark, setOnDark] = React.useState(false);
  const [condensed, setCondensed] = React.useState(false);
  const [navOpen, setNavOpen] = React.useState(false);
  const barRef = React.useRef(null);

  // The header floats over whatever is scrolling beneath it, and its
  // three pieces are light glass. Over an ink band they read as light
  // stickers laid on the page. Watch for a [data-ground="dark"] section
  // crossing the header's own band and flip the glass, not the layout,
  // so nothing shifts at the boundary.
  React.useEffect(() => {
    const darks = Array.from(document.querySelectorAll('[data-ground="dark"]'));
    let raf = null;
    const read = () => {
      raf = null;
      // Past the first screenful the three pills collapse to coins, so
      // the header stops sitting on the content it floats over.
      setCondensed(window.scrollY > 80);
      const bar = barRef.current;
      if (!bar || !darks.length) return;
      const b = bar.getBoundingClientRect();
      const line = b.top + b.height / 2;
      setOnDark(darks.some((el) => {
        const r = el.getBoundingClientRect();
        return r.top <= line && r.bottom >= line;
      }));
    };
    const queue = () => { if (raf === null) raf = requestAnimationFrame(read); };
    read();
    window.addEventListener("scroll", queue, { passive: true });
    window.addEventListener("resize", queue);
    return () => {
      window.removeEventListener("scroll", queue);
      window.removeEventListener("resize", queue);
      if (raf !== null) cancelAnimationFrame(raf);
    };
  }, []);


  // Close if the viewport crosses out of the menu range, so a resize
  // or a rotation cannot leave the panel hanging over a desktop layout.
  // 901 since step 9, and it has to stay in step with the media query in
  // styles.css that turns the pill into a coin.
  React.useEffect(() => {
    if (!window.matchMedia) return;
    const mq = window.matchMedia("(min-width: 901px)");
    const onChange = (e) => { if (e.matches) setNavOpen(false); };
    mq.addEventListener("change", onChange);
    return () => mq.removeEventListener("change", onChange);
  }, []);

  // Tapped open, it has to be dismissable: a tap outside or Escape.
  // Hover and focus close themselves, so this only matters for touch.
  React.useEffect(() => {
    if (!navOpen) return;
    const away = (e) => { if (!e.target.closest(".nav")) setNavOpen(false); };
    const key = (e) => { if (e.key === "Escape") setNavOpen(false); };
    document.addEventListener("pointerdown", away);
    document.addEventListener("keydown", key);
    return () => {
      document.removeEventListener("pointerdown", away);
      document.removeEventListener("keydown", key);
    };
  }, [navOpen]);

  const to = (hash) => (home ? hash : `index.html${hash}`);
  // Every link in the bar is a page now, so what is lit is simply which
  // page you are on. The in-page anchors — Method and Visit — came out
  // of the nav after step 9 at the client's request; `to()` still builds
  // the CTA's href, and `activeSection` is still accepted because the
  // home page passes it, but nothing in the bar lights from the scroll
  // spy any more.
  const pageCls = (id) => `nav-link${!home && page === id ? " active" : ""}`;

  return (
    <header className={`topbar${onDark ? " on-dark" : ""}${condensed ? " is-condensed" : ""}${navOpen ? " nav-open" : ""}`}>
      {/* Mobile only. Behind the panel, in front of the page. */}
      <div className="nav-scrim" onClick={() => setNavOpen(false)} aria-hidden="true" />
      <div className="topbar-inner" ref={barRef}>
        <a
          href={home ? "#top" : "index.html"}
          className="brand-mark"
          aria-label="IJWestern Realtors — home"
        >
          <img className="brand-logo" src="site-images/logo/ijw_logo_black.png" alt="IJWestern Realtors" />
          <span className="brand-word" aria-hidden="true"><span>IJWestern Realtors</span></span>
        </a>

        <nav className={`nav${navOpen ? " is-open" : ""}`}>
          {/* Hover and focus open the links in CSS. This is the tap
              equivalent, and the only way in on a touch screen. */}
          <button
            type="button"
            className="nav-coin"
            aria-label={navOpen ? "Close menu" : "Open menu"}
            aria-expanded={navOpen}
            onClick={() => setNavOpen((o) => !o)}
          >
            <span className="bars" aria-hidden="true">
              <span className="bar"></span><span className="bar"></span><span className="bar"></span>
            </span>
          </button>
          <span className="nav-items" onClick={() => setNavOpen(false)}>
            <a href="projects.html" className={pageCls("projects")} style={{ "--i": 0 }}>Projects</a>
            {/* Story left the home page in step 3 and its anchor went with
                it. This is the slot it left, now holding About — a real
                page since step 8, so the link is the same from anywhere. */}
            <a href="about.html"      className={pageCls("about")}    style={{ "--i": 1 }}>About</a>
            {/* Step 9. Last in the row, which is where a reader looks
                for it, and the only link here that is a page on every
                page including home. */}
            <a href="contact.html"    className={pageCls("contact")}  style={{ "--i": 2 }}>Contact</a>
            {/* Below 640 the bar has no room for a separate CTA, so it
                lives in the menu. Hidden above that, where the bar
                carries its own. */}
            <span className="nav-cta" style={{ "--i": 3 }}>
              <ScheduleButton onSchedule={onSchedule} href={to("#register")}
                              className="btn btn-primary btn-compact" />
            </span>
          </span>
        </nav>

        <div className="topbar-right">
          <ScheduleButton onSchedule={onSchedule} href={to("#register")} />
        </div>
      </div>
    </header>
  );
}

function Footer({ home = false, onSchedule = null }) {
  const to = (hash) => (home ? hash : `index.html${hash}`);
  const C = IJW_CONTACT;

  return (
    <footer className="footer" id="footer" data-ground="dark" data-screen-label="Footer">
      <div className="shell">
        <div className="footer-mark-row">
          <div className="footer-mark-block">
            {/* Client asked for the black mark in both header and footer
                (3 Sep). The logo is two-tone — solid block, knocked-out
                counters — so on this ink ground the black block reads as
                absence and only the white counters carry it. It sits on a
                light plate here so the mark keeps its silhouette. */}
            <div className="ijw-mark">
              <img className="ijw-logo" src="site-images/logo/ijw_logo_black.png" alt="" />
              <span className="ijw-name">IJWestern Realtors</span>
            </div>
            <p className="footer-pitch">
              Sensible land ownership, made easy.<br />
              <span style={{ color: "color-mix(in oklab, var(--ground-white) 55%, transparent)" }}>
                A small, accountable team. One company, every step.
              </span>
            </p>
          </div>
          <div className="footer-cta">
            {onSchedule ? (
              <button onClick={onSchedule} className="btn btn-primary btn-glass">
                Schedule a visit<span className="arrow"><ArrowIcon /></span>
              </button>
            ) : (
              <a href={to("#register")} className="btn btn-primary btn-glass">
                Schedule a visit<span className="arrow"><ArrowIcon /></span>
              </a>
            )}
          </div>
        </div>

        <div className="footer-top">
          <div className="footer-col">
            <h4>Visit</h4>
            <ul>
              <li><span>{C.address1}</span></li>
              <li><span>{C.address2}</span></li>
              <li><span>{C.hours}</span></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>Talk</h4>
            <ul>
              <li><a href={C.phoneHref}>{C.phone}</a></li>
              <li><a href={C.whatsapp} target="_blank" rel="noopener">WhatsApp ↗</a></li>
              <li><a href="contact.html">Contact</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>Follow</h4>
            <ul>
              <li><a href={C.instagram} target="_blank" rel="noopener">Instagram ↗</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>Legal</h4>
            <ul>
              <li><a href="#">Privacy</a></li>
              <li><a href="#">Terms</a></li>
            </ul>
          </div>
        </div>

        <div className="footer-bottom">
          <div>© 2026 IJWestern Realtors · Built in Palakkad</div>
          <div className="footer-bottom-right">
            <span>{C.coords}</span>
            {/* The home page's "Sitemap" link pointed at "#". There is no
                sitemap, so the dead link is gone rather than reproduced. */}
            {!home && (
              <>
                <span className="dot-sep">·</span>
                <a href="index.html">Home</a>
              </>
            )}
            <span className="dot-sep">·</span>
            <button type="button" className="footer-ck"
              onClick={() => window.ijwConsent && window.ijwConsent.open()}>
              Cookie settings
            </button>
          </div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { TopBar, Footer, IJW_CONTACT });
