/* eslint-disable */
const { useState, useEffect, useRef, useMemo } = React;

/* Multi-file navigation — each route is its own HTML file */
const AH_ROUTES = {
  home: "index.html",
  work: "work.html",
  services: "services.html",
  journal: "journal.html",
  "practice-team": "about.html",
  "practice-approach": "craftsmanship.html",
  "practice-process": "the-process.html",
  contact: "contact.html",
};

function hrefFor(to) {
  if (!to || to === "/" || to === "") return "index.html";
  const parts = to.replace(/^\//, "").split("/");
  // Dedicated category & service & journal-stream pages
  const direct = {
    residential: "residential.html",
    ecclesiastical: "ecclesiastical.html",
    institutional: "institutional.html",
    windows: "windows.html",
    doors: "doors.html",
    interiors: "interiors.html",
    "bespoke-design": "bespoke-design.html",
    consultancy: "consultancy.html",
    contact: "contact.html",
    about: "about.html",
    craftsmanship: "craftsmanship.html",
    "the-process": "the-process.html",
    privacy: "privacy.html",
  };
  if (direct[parts[0]] && parts.length === 1) return direct[parts[0]];
  // Project plate
  if (parts[0] === "work" && parts[1])
    return `plate.html?id=${encodeURIComponent(parts[1])}`;
  // About subpages
  if (parts[0] === "about") {
    const sub = parts[1] || "artifex";
    if (sub === "craftsmanship") return "craftsmanship.html";
    if (sub === "the-process" || sub === "working-with-us")
      return "the-process.html";
    return "about.html";
  }
  return "index.html";
}

function navigate(to) {
  window.location.href = hrefFor(to);
}

function Link({ to, className, children, ...rest }) {
  return (
    <a href={hrefFor(to)} className={className} {...rest}>
      {children}
    </a>
  );
}

function getParam(key) {
  return new URLSearchParams(window.location.search).get(key);
}

/* Current path inference for nav active state (based on filename) */
function currentSection() {
  const f = (
    window.location.pathname.split("/").pop() || "index.html"
  ).toLowerCase();
  if (f === "index.html" || f === "") return "/";
  if (
    f === "plate.html" ||
    ["residential.html", "ecclesiastical.html", "institutional.html"].includes(
      f
    )
  )
    return "/work";
  if (
    [
      "windows.html",
      "doors.html",
      "interiors.html",
      "bespoke-design.html",
      "consultancy.html",
    ].includes(f)
  )
    return "/services";
  if (f === "journal.html") return "/journal";
  if (
    f === "about.html" ||
    f === "craftsmanship.html" ||
    f === "the-process.html" ||
    f === "working-with-us.html"
  )
    return "/about";
  if (f === "contact.html") return "/contact";
  return "/";
}

/* ------------------------------------------------------------ NAV */
function NavItem({ to, label, isActive, items, openKey, setOpen, myKey }) {
  const open = openKey === myKey;
  // No dropdown — render as a real link (e.g. Contact)
  if (!items || items.length === 0) {
    return (
      <Link
        to={to}
        className={"ah-nav-link" + (isActive ? " is-active" : "")}
        onMouseEnter={() => setOpen(null)}
      >
        {label}
      </Link>
    );
  }
  // Has a dropdown — top label is non-clickable, hover opens menu
  return (
    <div
      className={"ah-nav-item" + (open ? " is-open" : "")}
      onMouseEnter={() => setOpen(myKey)}
    >
      <span
        className={
          "ah-nav-link ah-nav-link--label" + (isActive ? " is-active" : "")
        }
        role="button"
        aria-haspopup="true"
        aria-expanded={open}
        tabIndex={0}
      >
        {label}
      </span>
    </div>
  );
}

function Nav() {
  const path = currentSection();
  const isActive = (p) => path === p;
  const [openKey, setOpenKey] = useState(null);
  const [hoveredItem, setHoveredItem] = useState(null);

  // ---- Mobile drawer (≤768px) ----
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [accActiveKey, setAccActiveKey] = useState(null); // open accordion — touch tap-toggle only
  const burgerRef = useRef(null);
  const drawerRef = useRef(null);
  // Pointer devices drive the accordion + hover dimming purely via
  // :hover / :focus-within in CSS. Touch devices (no hover) fall back to a
  // JS tap-toggle. Detect capability once.
  const hoverCapableRef = useRef(
    typeof window !== "undefined" &&
      window.matchMedia &&
      window.matchMedia("(hover: hover) and (pointer: fine)").matches
  );

  const closeDrawer = () => {
    setDrawerOpen(false);
    setAccActiveKey(null);
    // Return focus to the menu icon on close.
    if (burgerRef.current) burgerRef.current.focus();
  };
  // The header burger toggles: opens when closed, closes when already open.
  const toggleDrawer = () => {
    setDrawerOpen((o) => {
      if (o) setAccActiveKey(null);
      return !o;
    });
  };

  // Reset hover when the dropdown switches/closes so each open starts on
  // the canonical first item again.
  useEffect(() => {
    setHoveredItem(null);
  }, [openKey]);

  // Drawer side-effects: lock page scroll, pause Lenis, Escape to close,
  // and move focus into the panel. All reversed on close.
  useEffect(() => {
    if (!drawerOpen) return;
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    if (window.__ahLenis && window.__ahLenis.stop) window.__ahLenis.stop();

    const onKey = (e) => {
      if (e.key === "Escape") closeDrawer();
    };
    document.addEventListener("keydown", onKey);

    const t = setTimeout(() => {
      const target =
        drawerRef.current &&
        drawerRef.current.querySelector(".ah-burger--close");
      if (target) target.focus();
    }, 60);

    return () => {
      document.body.style.overflow = prevOverflow;
      if (window.__ahLenis && window.__ahLenis.start) window.__ahLenis.start();
      document.removeEventListener("keydown", onKey);
      clearTimeout(t);
    };
  }, [drawerOpen]);

  // Pin the drawer + scrim top edge exactly to the header's bottom edge so
  // the header stays fully visible and interactive above the open drawer.
  useEffect(() => {
    const setTop = () => {
      const nav = document.querySelector(".ah-nav");
      if (nav) {
        document.documentElement.style.setProperty(
          "--ah-drawer-top",
          nav.getBoundingClientRect().bottom + "px"
        );
      }
    };
    setTop();
    window.addEventListener("resize", setTop);
    return () => window.removeEventListener("resize", setTop);
  }, []);

  const menus = {
    work: {
      label: "Selected Works",
      to: null,
      active: isActive("/work"),
      items: [
        { to: "/residential", label: "Residential", key: "residential" },
        {
          to: "/ecclesiastical",
          label: "Ecclesiastical",
          key: "ecclesiastical",
        },
        { to: "/institutional", label: "Institutional", key: "institutional" },
      ],
    },
    services: {
      label: "Services",
      to: null,
      active: isActive("/services"),
      items: [
        { to: "/windows", label: "Windows", key: "windows" },
        { to: "/doors", label: "Doors", key: "doors" },
        { to: "/interiors", label: "Interiors", key: "interiors" },
        { to: "/bespoke-design", label: "Bespoke", key: "bespoke" },
        { to: "/consultancy", label: "Consultancy", key: "consultancy" },
      ],
    },
    journal: { label: "The Journal", to: null, active: false, items: [] },
    about: {
      label: "About",
      to: null,
      active: isActive("/about"),
      items: [
        { to: "/about/artifex", label: "Artifex Heritage", key: "team" },
        { to: "/about/craftsmanship", label: "Craftsmanship", key: "approach" },
        { to: "/about/the-process", label: "The Process", key: "the-process" },
      ],
    },
  };

  const activeMenu = openKey ? menus[openKey] : null;

  // Drawer top-level items — same set + order as the desktop header. Items
  // with children render as accordions; Contact (no children) navigates.
  const drawerItems = [
    { key: "work", label: menus.work.label, items: menus.work.items },
    {
      key: "services",
      label: menus.services.label,
      items: menus.services.items,
    },
    { key: "about", label: menus.about.label, items: menus.about.items },
    { key: "contact", label: "Contact", to: "/contact", items: [] },
  ];

  return (
    <header
      className={"ah-nav" + (openKey ? " has-drop" : "")}
      onMouseLeave={() => setOpenKey(null)}
    >
      <div className="ah-nav-inner">
        <nav className="ah-nav-links">
          <NavItem
            to={menus.work.to}
            label={menus.work.label}
            isActive={menus.work.active}
            items={menus.work.items}
            myKey="work"
            openKey={openKey}
            setOpen={setOpenKey}
          />
          <NavItem
            to={menus.services.to}
            label={menus.services.label}
            isActive={menus.services.active}
            items={menus.services.items}
            myKey="services"
            openKey={openKey}
            setOpen={setOpenKey}
          />
          <NavItem
            to={menus.about.to}
            label={menus.about.label}
            isActive={menus.about.active}
            items={menus.about.items}
            myKey="about"
            openKey={openKey}
            setOpen={setOpenKey}
          />
          <Link
            to="/contact"
            className={
              "ah-nav-link ah-nav-cta" +
              (isActive("/contact") ? " is-active" : "")
            }
            onMouseEnter={() => setOpenKey(null)}
          >
            Contact
          </Link>
        </nav>
        <div className="ah-nav-brand">
          <Link to="/" className="ah-wordmark">
            <img
              src="src/assets/logo-wordmark.png"
              alt="Artifex Heritage"
              className="ah-wordmark-img"
            />
          </Link>
        </div>

        <button
          ref={burgerRef}
          type="button"
          className="ah-burger"
          aria-label="Menu"
          aria-haspopup="true"
          aria-expanded={drawerOpen}
          aria-controls="ah-mobile-drawer"
          onClick={toggleDrawer}
        >
          <span className="ah-burger-glyph">
            <i></i>
            <i></i>
            <i></i>
          </span>
        </button>
      </div>

      <div className={"ah-nav-panel" + (activeMenu ? " is-open" : "")}>
        <div className="ah-nav-panel-inner">
          <div className="ah-nav-panel-list" style={{ fontWeight: "500" }}>
            {activeMenu &&
              activeMenu.items.map((it, i) => (
                <Link
                  key={i}
                  to={it.to}
                  className="ah-nav-panel-link"
                  onMouseEnter={
                    it.key ? () => setHoveredItem(it.key) : undefined
                  }
                >
                  {it.label}
                </Link>
              ))}
          </div>

          {activeMenu &&
            activeMenu.items.length > 0 &&
            activeMenu.items[0].key && (
              <div className="ah-nav-img-stack" aria-hidden="true">
                {activeMenu.items.map((it) => {
                  const activeItemKey = hoveredItem || activeMenu.items[0].key;
                  return (
                    <a
                      key={it.key}
                      href={hrefFor(it.to)}
                      className={
                        "ah-nav-img-link" +
                        (activeItemKey === it.key ? " is-active" : "")
                      }
                      onClick={(e) => {
                        const slot =
                          e.currentTarget.querySelector("image-slot");
                        if (slot && !slot.hasAttribute("data-filled")) {
                          // Empty: let image-slot's own click handler open the file picker.
                          e.preventDefault();
                        }
                        // Populated: anchor navigates as normal.
                      }}
                    >
                      <image-slot
                        id={`nav-${openKey}-${it.key}`}
                        shape="rect"
                        placeholder=""
                      />
                    </a>
                  );
                })}
              </div>
            )}
        </div>
      </div>

      {/* ---- Mobile drawer (≤768px) — right-edge slide-in ---- */}
      <div
        className={"ah-mdrawer-scrim" + (drawerOpen ? " is-open" : "")}
        onClick={closeDrawer}
        aria-hidden="true"
      />
      <aside
        id="ah-mobile-drawer"
        ref={drawerRef}
        className={"ah-mdrawer" + (drawerOpen ? " is-open" : "")}
        role="dialog"
        aria-modal="true"
        aria-label="Menu"
        aria-hidden={!drawerOpen}
      >
        <button
          type="button"
          className="ah-burger ah-burger--close"
          aria-label="Close menu"
          onClick={closeDrawer}
        >
          <span className="ah-burger-glyph" data-open="true">
            <i></i>
            <i></i>
            <i></i>
          </span>
        </button>

        <div className="ah-mdrawer-scroll">
          <nav className="ah-mdrawer-nav">
            {drawerItems.map((g) => {
              const hasChildren = g.items && g.items.length > 0;
              const active = accActiveKey === g.key;
              if (!hasChildren) {
                return (
                  <div className="ah-mdrawer-group" key={g.key}>
                    <Link
                      to={g.to}
                      className="ah-mdrawer-parent"
                      onClick={closeDrawer}
                    >
                      {g.label}
                    </Link>
                  </div>
                );
              }
              return (
                <div
                  className={"ah-mdrawer-group" + (active ? " is-active" : "")}
                  key={g.key}
                >
                  <button
                    type="button"
                    className="ah-mdrawer-parent"
                    aria-expanded={active}
                    onClick={() => {
                      if (!hoverCapableRef.current)
                        setAccActiveKey((k) => (k === g.key ? null : g.key));
                    }}
                  >
                    {g.label}
                  </button>
                  <div className="ah-mdrawer-childwrap">
                    <div className="ah-mdrawer-children">
                      {g.items.map((it, i) => (
                        <Link
                          key={i}
                          to={it.to}
                          className="ah-mdrawer-child"
                          onClick={closeDrawer}
                        >
                          {it.label}
                        </Link>
                      ))}
                    </div>
                  </div>
                </div>
              );
            })}
          </nav>

          <div className="ah-mdrawer-foot">
            <a
              href="mailto:info@artifexheritage.com"
              className="ah-mdrawer-foot-email"
            >
              info@artifexheritage.com
            </a>
            <div className="ah-mdrawer-foot-links">
              <a
                href="https://www.instagram.com/artifexheritage/"
                target="_blank"
                rel="noreferrer"
              >
                Instagram
              </a>
              <a
                href="https://www.linkedin.com/company/artifex-heritage/"
                target="_blank"
                rel="noopener noreferrer"
              >
                LinkedIn
              </a>
            </div>
          </div>
        </div>
      </aside>
    </header>
  );
}

/* ------------------------------------------------------------ SEAL */
function SealRow() {
  return null;
}

/* ------------------------------------------------------------ FOOTER */
function Footer() {
  return (
    <footer className="ah-footer">
      <div className="ah-footer-inner">
        <div className="ah-footer-col">
          <h3 className="ah-footer-head">Information</h3>
          <div className="ah-footer-body">
            <ul>
              <li>
                <Link to="/about">Artifex Heritage</Link>
              </li>
              <li>
                <Link to="/craftsmanship">Craftsmanship</Link>
              </li>
              <li>
                <Link to="/the-process">The Process</Link>
              </li>
              <li>
                <Link to="/privacy">Privacy Policy</Link>
              </li>
            </ul>
          </div>
        </div>
        <div className="ah-footer-col ah-footer-col--brand">
          <img src="src/assets/logo-wide.svg" alt="Artifex Heritage" className="ah-footer-logo" />
          <div className="ah-footer-body">
            <p style={{ color: "var(--color-ink)", maxWidth: "60ch", margin: 0 }}>
              A heritage conservation practice, committed to repair over
              replacement. Restoring buildings and artifacts of architectural,
              cultural, and historical significance.
            </p>
          </div>
        </div>
        <div className="ah-footer-col">
          <h3 className="ah-footer-head">Contact</h3>
          <div className="ah-footer-body">
            <ul>
              <li>
                <a href="mailto:info@artifexheritage.com">
                  info@artifexheritage.com
                </a>
              </li>
              <li>
                <a href="tel:+16138584211">(613) 858 4211</a>
              </li>
              <li>
                <a
                  href="https://www.instagram.com/artifexheritage/"
                  target="_blank"
                  rel="noreferrer"
                >
                  Instagram
                </a>
              </li>
              <li>
                <a
                  href="https://www.linkedin.com/company/artifex-heritage/"
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  LinkedIn
                </a>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <div className="ah-footer-copy">© MMXXVI Artifex Heritage Ltd.</div>
    </footer>
  );
}

/* ------------------------------------------------------------ Shared */
function Img({ variant = "warm", aspect, style }) {
  return (
    <div
      className={`ah-img ah-img--${variant}`}
      style={{ aspectRatio: aspect, ...style }}
    />
  );
}

function ProjectTile({ project, compact }) {
  return (
    <Link to={`/work/${project.id}`} className="ah-tile">
      <div className="ah-tile-figure">
        <Img variant={project.img} />
      </div>
      <div className="ah-tile-caption">
        <div className="ah-tile-title">
          {project.titleItalic ? <em>{project.title}</em> : project.title}
          {project.representative && (
            <span
              style={{
                color: "var(--color-ink)",
                fontFamily: "'Inter', sans-serif",
                fontSize: 10.5,
                fontStyle: "normal",
                letterSpacing: "0.12em",
                textTransform: "uppercase",
                marginLeft: 8,
                verticalAlign: "middle",
              }}
            >
              [representative]
            </span>
          )}
        </div>
        {!compact && (
          <>
            <div className="ah-tile-sub">
              {project.location} · {project.era}
            </div>
            <div className="ah-tile-disc">{project.discipline}</div>
          </>
        )}
      </div>
    </Link>
  );
}

function Accordion({ label, children, mark, defaultOpen }) {
  const [open, setOpen] = useState(!!defaultOpen);
  return (
    <div className="ah-acc">
      <button className="ah-acc-head" onClick={() => setOpen((o) => !o)}>
        <span className="ah-acc-head-left">
          {mark && <span className="ah-acc-mark">{mark}</span>}
          <span>{label}</span>
        </span>
        <span className="ah-acc-plus">{open ? "\u2013" : "+"}</span>
      </button>
      {open && <div className="ah-acc-body">{children}</div>}
    </div>
  );
}

/* Page shell — wraps a screen with Nav/Footer/TweaksPanel */
function Page({ children }) {
  React.useEffect(() => {
    // Page-tinted body: extend the active page's bg color (cream / mist) onto the body
    // so the footer (which sits outside the page wrapper) inherits the same tint.
    const sync = () => {
      const wrap = document.querySelector(
        ".ah-bg-cream, .ah-bg-mist, .ah-bg-paper, .ah-bg-sage"
      );
      if (!wrap) {
        document.body.style.background = "";
        return;
      }
      document.body.style.background = getComputedStyle(wrap).backgroundColor;
    };
    sync();
    return () => {
      document.body.style.background = "";
    };
  });

  // Expose the wrap so any other effect (e.g. MagazineArticle's JS reflow)
  // can re-run it after moving paragraphs between containers.
  function ahWrapDropcap() {
    const findFirstText = (node) => {
      if (!node) return null;
      if (node.nodeType === Node.TEXT_NODE) return node;
      for (const child of node.childNodes) {
        const found = findFirstText(child);
        if (found) return found;
      }
      return null;
    };
    document.querySelectorAll("p.ah-drop").forEach((p) => {
      if (p.querySelector(".ah-dropcap")) return;
      const textNode = findFirstText(p);
      if (!textNode) return;
      const text = textNode.textContent;
      if (!text || !text.length) return;
      const span = document.createElement("span");
      span.className = "ah-dropcap";
      span.textContent = text.charAt(0);
      textNode.textContent = text.slice(1);
      textNode.parentNode.insertBefore(span, textNode);
    });
  }
  window.__ahWrapDropcap = ahWrapDropcap;

  React.useEffect(() => {
    // Drop cap — wrap the first character of every `.ah-drop` paragraph in
    // a real <span class="ah-dropcap"> element. See ahWrapDropcap above.
    ahWrapDropcap();
  });

  React.useEffect(() => {
    // Smooth-scroll engine — same family as mfisher.com (Lenis).
    // Loaded once per document, with a settle-easing curve.
    if (window.__ahLenisStarted) return;
    window.__ahLenisStarted = true;

    const start = () => {
      if (!window.Lenis) return;
      const lenis = new window.Lenis({
        duration: 1.2,
        easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)),
        smoothWheel: true,
        smoothTouch: false,
        wheelMultiplier: 1,
        touchMultiplier: 1.5,
      });
      window.__ahLenis = lenis;
      function raf(time) {
        lenis.raf(time);
        requestAnimationFrame(raf);
      }
      requestAnimationFrame(raf);
    };

    if (window.Lenis) {
      start();
    } else {
      const s = document.createElement("script");
      s.src =
        "https://unpkg.com/@studio-freight/lenis@1.0.42/dist/lenis.min.js";
      s.onload = start;
      document.head.appendChild(s);
    }
  }, []);

  return (
    <div>
      <Nav />
      {children}
      <Footer />
      <TweaksPanel />
    </div>
  );
}

/* Shared full-viewport hero — breadcrumb + title + italic strap + gradient panel.
   Used by Services subpages and Selected Works category pages. */
function PageHero({ breadcrumb, title, strap, hero = "sand" }) {
  return (
    <div className="ah-fullvh-hero">
      <section className="ah-page ah-svc-head">
        <div className="ah-svc-titlerow">
          <h1 className="ah-svc-title">{title}</h1>
          {strap && <span className="ah-svc-tagline">{strap}</span>}
        </div>
      </section>

      <section className="ah-svc-hero-wrap">
        <div className={`ah-svc-hero ah-img ah-img--${hero}`} />
      </section>
    </div>
  );
}

Object.assign(window, {
  navigate,
  Link,
  hrefFor,
  getParam,
  Nav,
  SealRow,
  Footer,
  Img,
  ProjectTile,
  Accordion,
  Page,
  PageHero,
});
