/* Backentra — shared site chrome. One header and one footer for the homepage and every
   sub-page, so navigation and the footer never disappear when you open one. Loaded
   before the pages that use them.
   window.BackentraSiteHeader, window.BackentraSiteFooter */
const SH = window.BackentraDesignSystem_93cf3a;
const { Button: SHBtn, Icon: SHIcon } = SH;

/* Where the marketing site hands off to the application. Nothing renders it today: the
   header Sign-in CTA, the site's Demo page and the full-account modal have all been
   removed, which leaves only the footer's "@webapp" branch below, and SH_FOOT currently
   has no entry that uses that key. Kept, rather than deleted, because the handoff URL is
   the sort of thing that gets re-derived wrongly the moment it is needed again.

   The #demo fragment is load-bearing when it IS used: the app's sign-in screen opens the
   invite-key gate directly when it sees the fragment, instead of landing the visitor on
   the password form.

   Absolute and branded on purpose. It leaves this origin, so a relative path would 404,
   and the raw Vercel deployment URL would show a customer a hostname that is not ours. */
const SH_APP_ORIGIN = "https://app.backentra.com";
const SH_APP_SIGNIN = SH_APP_ORIGIN + "/sign-in#demo";
window.BK_APP_ORIGIN = SH_APP_ORIGIN;
window.BK_APP_SIGNIN = SH_APP_SIGNIN;

/* Backentra lockup, drawn rather than fetched. `tone` picks the surface it sits on. */
function BKLogo({ height, tone }) {
  const h = height || 34;
  const dark = tone === "dark";
  const ink = dark ? "#FFFFFF" : "var(--navy-900)";
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: h * 0.3, height: h, lineHeight: 1 }}>
      <svg width={h * 0.86} height={h} viewBox="0 0 168 176" fill="none" aria-hidden="true" style={{ display: "block", flex: "none" }}>
        <path fill={ink} d="M44 16 L118 16 C138 16 152 30 152 52 C152 74 146 84 140 88 C146 92 152 104 152 124 C152 146 138 176 118 176 L46 176 C43 176 42 175 42 172 L42 154 C42 151 43 150 46 150 L114 150 C124 150 124 138 124 124 C124 110 118 104 108 104 L80 104 C77 104 76 103 76 100 L76 84 C76 81 77 80 80 80 L118 80 C120 74 124 70 124 56 C124 40 118 40 108 40 L46 40 C43 40 42 39 42 36 L42 20 C42 17 43 16 46 16 Z" />
        <rect fill="var(--accent)" x="6" y="53" width="60" height="17" rx="8.5" />
        <rect fill="var(--accent)" x="24" y="84" width="37" height="17" rx="8.5" />
        <rect fill="var(--accent)" x="6" y="116" width="60" height="17" rx="8.5" />
      </svg>
      <span style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: h * 0.72, letterSpacing: "-0.035em", color: dark ? "#fff" : "var(--navy-900)" }}>Backentra</span>
    </span>
  );
}

/* label -> page key. "home" returns to the marketing page. */
const SH_NAV = [
  ["Product", "product"],
  ["Pricing", "plans"],
  ["Founding Members", "founding"],
  ["Blog", "blog"],
  ["Preview", "preview"],  ["About", "about"],
  ["Join the List", "join"],
];

/* ---------- Routing: page key <-> real URL ----------
   Loaded before every page component, so header/footer links (and site.jsx's router,
   which loads last) share one mapping instead of each guessing at paths independently.
   "referral" is deliberately absent: it has no working backend and is not linked from
   anywhere public (see referral.jsx), so it stays reachable only by the internal page key
   the app already had, not by a public URL — hitting /referral returns the site's normal
   404 rather than a page nobody meant to publish. "pipeline" (How It Works) IS routed:
   it is real, finished content that predates this pass, just not yet linked from the nav. */
const SH_ROUTES = [
  ["product", "/product"],
  ["plans", "/pricing"],
  ["founding", "/founding-members"],
  ["join", "/join"],
  ["enterprise", "/enterprise"],
  ["preview", "/preview"],
  ["about", "/about"],
  ["privacy", "/privacy"],
  ["terms", "/terms"],
  ["blog", "/blog"],
  ["pipeline", "/how-it-works"],
];
const SH_KEY_TO_PATH = {};
const SH_PATH_TO_KEY = {};
SH_ROUTES.forEach(([k, p]) => { SH_KEY_TO_PATH[k] = p; SH_PATH_TO_KEY[p] = k; });

function bkPageToPath(key) {
  if (!key || key === "home") return "/";
  if (typeof key === "string" && key.indexOf("blog-") === 0) return "/blog/" + key.slice(5);
  return SH_KEY_TO_PATH[key] || "/";
}

/* "notfound" is a real return value, not an absence of one: it tells the router to render
   the 404 page rather than silently falling back to the homepage, which is how a broken
   link used to look identical to a working one. */
function bkPathToPage(pathname) {
  let p = String(pathname || "/").replace(/\/+$/, "");
  if (p === "") p = "/";
  if (p === "/") return "home";
  if (SH_PATH_TO_KEY[p]) return SH_PATH_TO_KEY[p];
  if (p.indexOf("/blog/") === 0 && p.length > 6) return "blog-" + p.slice(6);
  return "notfound";
}
window.BackentraPageToPath = bkPageToPath;
window.BackentraPathToPage = bkPathToPage;

/* ---------- Per-page <head> metadata ----------
   index.html carries the homepage's tags statically (so the very first response, before
   any JS runs, already describes the homepage correctly to a crawler or a share preview).
   Every other page updates the same tags in place once it mounts. Only tags that already
   exist in index.html are touched — this never creates new <meta> elements, so a typo in
   a key here fails silently rather than littering the head with duplicates. */
function bkSetMeta(meta) {
  const base = "https://www.backentra.com";
  const path = (meta && meta.path) || "/";
  const url = base + path;
  const title = (meta && meta.title) || "Backentra — The backbone of your business";
  const description = (meta && meta.description) ||
    "Backentra is the backbone of your business: jobs, schedule, clients and invoicing in one place for service businesses. Founding members lock 25% for life.";
  const robots = (meta && meta.robots) || "index, follow, max-image-preview:large, max-snippet:-1";
  document.title = title;
  const set = (selector, attr, value) => {
    const el = document.head.querySelector(selector);
    if (el) el.setAttribute(attr, value);
  };
  set('link[rel="canonical"]', "href", url);
  set('meta[name="robots"]', "content", robots);
  set('meta[name="description"]', "content", description);
  set('meta[property="og:title"]', "content", title);
  set('meta[property="og:description"]', "content", description);
  set('meta[property="og:url"]', "content", url);
  set('meta[name="twitter:title"]', "content", title);
  set('meta[name="twitter:description"]', "content", description);
}
window.BackentraSetMeta = bkSetMeta;

function PreLaunchBanner() {
  return (
    <div className="bk-prelaunch" style={{ background: "var(--navy-950)", color: "var(--gray-300)", padding: "9px 0", borderBottom: "1px solid var(--border-inverse)" }}>
      <div style={{ maxWidth: "var(--container-max)", margin: "0 auto", padding: "0 32px", display: "flex", alignItems: "center", justifyContent: "center", gap: 11, flexWrap: "wrap", textAlign: "center" }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "3px 9px", borderRadius: "var(--radius-pill)", background: "var(--accent-solid)", color: "#fff", fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 10.5, letterSpacing: ".06em", flex: "none" }}>
          <SHIcon name="hard-hat" size={12} /> IN DEVELOPMENT
        </span>
        <span style={{ fontSize: 13, lineHeight: 1.5 }}>
          Backentra is a work in progress. Everything on this site, including features, pricing and integrations, is subject to change before launch.
        </span>
      </div>
    </div>
  );
}

function SiteHeader({ current, onNav }) {
  const go = (key) => (e) => { e.preventDefault(); if (onNav) onNav(key); };
  return (
    <React.Fragment>
    <PreLaunchBanner />
    <header style={{ position: "sticky", top: 0, zIndex: 20, background: "rgba(255,255,255,0.92)", backdropFilter: "blur(8px)", borderBottom: "1px solid var(--border)" }}>
      <div style={{ maxWidth: "var(--container-max)", margin: "0 auto", padding: "10px 32px", display: "grid", gridTemplateColumns: "auto minmax(0, 1fr) auto", alignItems: "center", columnGap: 26, minHeight: 68 }}>
        <a href="/" onClick={go("home")} aria-label="Backentra" style={{ display: "inline-flex", flex: "none" }}>
          <BKLogo height={32} />
        </a>
        <nav style={{ display: "flex", alignItems: "center", flexWrap: "wrap", gap: "6px 22px", marginLeft: 10, minWidth: 0 }}>
          {SH_NAV.map(([label, key]) => {
            const on = current === key;
            return <a key={key} href={bkPageToPath(key)} onClick={go(key)} style={{
              position: "relative", whiteSpace: "nowrap",
              color: on ? "var(--text-strong)" : "var(--text-body)",
              fontFamily: "var(--font-display)", fontSize: 15,
              fontWeight: on ? 700 : 500,
              paddingBottom: 2,
              borderBottom: "2px solid " + (on ? "var(--accent)" : "transparent"),
            }}>{label}</a>;
          })}
        </nav>
        <span style={{ justifySelf: "end" }}>
          {/* No sign-in pre-launch: there is nothing to sign in to, and a button that opened
              a gate nobody has a key for was worse than no button. Joining the founding list
              is the one action that does something today. */}
          <a href="/join" onClick={go("join")} style={{ display: "inline-flex", alignItems: "center", gap: 8, height: 44, padding: "0 20px",
            borderRadius: "var(--radius-md)", background: "var(--accent-solid)", color: "#fff", fontFamily: "var(--font-display)",
            fontWeight: 600, fontSize: 18, textDecoration: "none", whiteSpace: "nowrap" }}>
            Join the list <SHIcon name="arrow-right" size={18} color="#fff" />
          </a>
        </span>
      </div>
    </header>
    </React.Fragment>
  );
}

/* Footer labels map to the same page keys the header uses. */
const SH_FOOT = [
  ["Product", [["Product", "product"], ["Pricing", "plans"], ["Preview", "preview"]]],
  ["Company", [["About", "about"], ["Blog", "blog"], ["Contact", "about"], ["Founding Members", "founding"]]],
  ["Legal", [["Privacy Policy", "privacy"], ["Terms of Service", "terms"]]],
];

function SiteFooter({ onNav }) {
  const wrap = { maxWidth: "var(--container-max)", margin: "0 auto", padding: "0 32px" };
  const hit = (key) => (e) => { e.preventDefault(); if (key && onNav) onNav(key); };
  return (
    <footer style={{ background: "var(--navy-950)", color: "var(--gray-400)", padding: "56px 0 32px" }}>
      <div style={{ ...wrap, display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr 1fr", gap: 32 }}>
        <div>
          <a href="/" onClick={hit("home")} aria-label="Backentra" style={{ display: "inline-flex", marginBottom: 14 }}>
            <BKLogo height={32} tone="dark" />
          </a>
          <p style={{ maxWidth: 260, fontSize: 14, lineHeight: 1.6, margin: 0 }}>The backbone of your business. Built for the people who build, fix, and get the job done.</p>
        </div>
        {SH_FOOT.map(([heading, links]) => (
          <div key={heading}>
            <div style={{ color: "#fff", fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 13, letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: 14 }}>{heading}</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {/* "@webapp" leaves the marketing site for the application, so it is a real href
                  rather than a page key the router would have no destination for. */}
              {links.map(([label, key]) => key === "@webapp"
                ? <a key={label} href={SH_APP_SIGNIN} style={{ color: "var(--gray-400)", fontSize: 14, textDecoration: "none" }}>{label}</a>
                : <a key={label} href={bkPageToPath(key)} onClick={hit(key)} style={{ color: "var(--gray-400)", fontSize: 14 }}>{label}</a>)}
            </div>
          </div>
        ))}
      </div>
      <div style={{ ...wrap, marginTop: 40, paddingTop: 20, borderTop: "1px solid var(--border-inverse)", display: "flex", justifyContent: "space-between", gap: 16, flexWrap: "wrap", fontSize: 13 }}>
        <span>© 2026 Backentra. All rights reserved.</span>
        <span style={{ display: "flex", gap: 16 }}>
          <a href="/privacy" onClick={hit("privacy")} style={{ color: "var(--gray-400)" }}>Privacy</a>
          <a href="/terms" onClick={hit("terms")} style={{ color: "var(--gray-400)" }}>Terms</a>
        </span>
      </div>
    </footer>
  );
}

/* Brand pillars. Lead sentence is canonical from guidelines/brand/brand-voice.card.html.
   Every surface uses these; never paraphrase the lead. */
const SH_PILLARS = [
  ["shield", "Dependable", "Strong foundation and support.", "Your data, jobs and money are safe and always available."],
  ["layers", "Structured", "Organized, efficient, and reliable.", "Every job flows from quote to schedule to paid."],
  ["trending-up", "Built to Scale", "Secure, scalable, and future-ready.", "Add crew, locations and services without the chaos."],
];

window.BackentraLogo = BKLogo;
window.BackentraPreLaunchBanner = PreLaunchBanner;
window.BackentraPillars = SH_PILLARS;
window.BackentraSiteHeader = SiteHeader;
window.BackentraSiteFooter = SiteFooter;
