// site-pages.jsx — inner pages, rectilinear style matching the home page.
// Dark canvas, max-width frame, big display headlines, cream tiles with
// asymmetric corners, centered section headers, simple "Learn more →" links.

// ── content ────────────────────────────────────────────────────────────────
// Loaded from /content/*.md by content-loader.js (YAML frontmatter). The
// hard-coded literals below are baked-in fallbacks so the site still renders
// if the markdown fetch fails. To edit content for any of these pages, edit
// the corresponding file under /content/ — not the values here.
const __SP_BX = (typeof window !== "undefined" && window.__BX_CONTENT) || {};
const __spServices = (__SP_BX.services && __SP_BX.services.services) || null;
const __spWork     = (__SP_BX.work && __SP_BX.work.industries) || null;
const __spOss      = (__SP_BX["open-source"] && __SP_BX["open-source"].oss) || null;
const __spPosts    = (__SP_BX.blog && __SP_BX.blog.posts) || null;
const __spServicesData = __SP_BX.services || {};
const __spWorkData     = __SP_BX.work || {};
const __spOssData      = __SP_BX["open-source"] || {};
const __spPostsData    = __SP_BX.blog || {};
const __spAboutData    = __SP_BX.about || {};
const __spCareersData  = __SP_BX.careers || {};
const __spContactData  = __SP_BX.contact || {};

const SITE_CONTENT = {
  services: __spServices || [],
  industries: __spWork || [],
  oss: __spOss || [],
  posts: __spPosts || [],
  servicesMeta: __spServicesData,
  workMeta: __spWorkData,
  ossMeta: __spOssData,
  postsMeta: __spPostsData,
  aboutMeta: __spAboutData,
  careersMeta: __spCareersData,
  contactMeta: __spContactData,
};

window.SITE_CONTENT = SITE_CONTENT;

// ──────────────────────────────────────────────────────────────────────────
// Shared page styles
// ──────────────────────────────────────────────────────────────────────────
window.SiteStyles = "";

// ──────────────────────────────────────────────────────────────────────────
function PageHero({ h1 }) {
  return (
    <header className="sp-hero">
      {typeof h1 === 'string' ? <h1 dangerouslySetInnerHTML={{ __html: h1 }} /> : <h1>{h1}</h1>}
    </header>
  );
}



function getCaseStudies() {
  const bx = (typeof window !== "undefined" && window.__BX_CONTENT) || {};

  const padiMd = bx["case-padi"] || {};
  const cymbiotikaMd = bx["case-cymbiotika"] || {};
  const viasatMd = bx["case-viasat"] || {};

  return [
    {
      slug: "padi",
      theme: "cs-padi",
      eyebrow: padiMd.eyebrow || "",
      meta: padiMd.meta || "",
      title: padiMd.title || "",
      body: padiMd.body || "",
      ctaUrl: padiMd.ctaUrl || "",
      ctaLabel: padiMd.ctaLabel || "",
      shotLabel: padiMd.shotLabel || "",
    },
    {
      slug: "cymbiotika",
      theme: "cs-cymbiotika",
      eyebrow: cymbiotikaMd.eyebrow || "",
      meta: cymbiotikaMd.meta || "",
      title: cymbiotikaMd.title || "",
      body: cymbiotikaMd.body || "",
      ctaUrl: cymbiotikaMd.ctaUrl || "",
      ctaLabel: cymbiotikaMd.ctaLabel || "",
      shotLabel: cymbiotikaMd.shotLabel || "",
    },
  ];
}

function CaseStudiesSection() {
  return (
    <>
      <section className="sp-section pt-0 pb-0">
        <div className="sp-section-head" style={{ borderTop: "none" }}>
          <h2 dangerouslySetInnerHTML={{ __html: SITE_CONTENT.workMeta?.sectionTitle || "" }} />
        </div>
      </section>

      {getCaseStudies().map((cs) => (
        <CaseStudy key={cs.slug} {...cs} />
      ))}
    </>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Services
// ──────────────────────────────────────────────────────────────────────────
function PageServices() {
  const meta = SITE_CONTENT.servicesMeta || {};
  window.useSEO({
    title: meta.metaTitle,
    description: meta.metaDescription
  });
  const tones = ["t-cream-1", "t-cream-2", "t-cream-3"];
  return (
    <div className="bx-page site-page">
            <Nav />
      <div className="sp-frame">
        <PageHero
          h1={meta.title || ""}
        />

        <section className="sp-section">
          <div className="sp-section-head">
            <h2 dangerouslySetInnerHTML={{ __html: SITE_CONTENT.servicesMeta?.sectionTitle || "" }} />
          </div>
          <div className="sp-svc-grid">
            {SITE_CONTENT.services.map((s, i) => (
              <article key={s.n} className={`sp-card ${tones[i % tones.length]}`}>
                <div className="sp-num">{s.n}</div>
                <h3>{s.title}</h3>
                <div className="sp-body">
                  <p>{s.body}</p>
                  <div className="sp-phases">
                    {s.phases.map((p) => (
                      <div key={p} className="phase-tile">
                        <div className="pt-label">{p}</div>
                      </div>
                    ))}
                  </div>
                </div>
              </article>
            ))}
          </div>
        </section>

        <section className="sp-section">
          <div className="sp-section-head">
            <h2 dangerouslySetInnerHTML={{ __html: SITE_CONTENT.servicesMeta?.capabilitiesTitle || "" }} />
          </div>
          <div className="sp-caps-grid">
            {(SITE_CONTENT.servicesMeta?.capabilities || []).map((cap, i) => {
              const tones = ["t-cream-1", "t-cream-2", "t-cream-3"];
              const tone = tones[i % tones.length];
              return (
                <article key={cap.name} className={`sp-cap-card ${tone}`}>
                  <div className="cap-num">{cap.n || cap.num}</div>
                  <h3>{cap.name}</h3>
                  <p>{cap.body || cap.desc}</p>
                </article>
              );
            })}
          </div>
        </section>

        <CaseStudiesSection />
      </div>
      <Footer />
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Open source
// ──────────────────────────────────────────────────────────────────────────
function PageOpenSource() {
  const meta = SITE_CONTENT.ossMeta || {};
  window.useSEO({
    title: meta.metaTitle,
    description: meta.metaDescription
  });
  const tones = ["t-cream-1", "t-cream-2", "t-cream-3", "t-cream-1", "t-cream-2", "t-cream-3"];
  return (
    <div className="bx-page site-page">
            <Nav />
      <div className="sp-frame">
        <PageHero
          h1={SITE_CONTENT.ossMeta?.title || ""}
        />

        <section className="sp-section">
          <div className="sp-section-head">
            <h2 dangerouslySetInnerHTML={{ __html: SITE_CONTENT.ossMeta?.sectionTitle || "" }} />
          </div>
          <div className="sp-oss-grid">
            {SITE_CONTENT.oss.map((o, i) => (
              <article key={o.name} className={`sp-card ${tones[i]}`}>
                <div className="sp-num">{o.n}</div>
                <h3>{o.name}</h3>
                <div className="sp-body">
                  <p>{o.desc}</p>
                  <a 
                    className="sp-learn" 
                    href={o.ctaUrl || o.linkUrl} 
                    target="_blank" 
                    rel="noopener noreferrer"
                  >
                    {o.ctaLabel || o.linkText}
                  </a>
                </div>
              </article>
            ))}
          </div>
        </section>

        <RecursicaBlock />
      </div>
      <Footer />
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Industries (work)
// ──────────────────────────────────────────────────────────────────────────
function PageWork() {
  const meta = SITE_CONTENT.workMeta || {};
  window.useSEO({
    title: meta.metaTitle,
    description: meta.metaDescription
  });
  return (
    <div className="bx-page site-page">
            <Nav />
      <div className="sp-frame">
        <PageHero
          h1={meta.title ? <span dangerouslySetInnerHTML={{ __html: meta.title }} /> : null}
        />

        <section className="sp-section">
          <div className="sp-section-head">
            <h2>{meta.introTitle ? <span dangerouslySetInnerHTML={{ __html: meta.introTitle }} /> : null}</h2>
          </div>
          {SITE_CONTENT.industries.map((ind, i) => (
            <article key={ind.slug} id={ind.slug} className={`ind-block industry-${ind.slug}`}>
              <div className="ind-text">
                <div>
                  <div className="ind-num">{String(i + 1).padStart(2, "0")}</div>
                  <h2>{ind.name.replace(/Cybersecurity/, "Cyber\u00ADsecurity")}.</h2>
                </div>
                {(ind.body || ind.desc) && <p>{ind.body || ind.desc}</p>}
              </div>
              <div className="ind-proof">
                {ind.proof.map((p, j) => (
                  <div key={p.k} className="pcard">
                    <div className="k">{p.k}</div>
                    <div className="v">{p.v}</div>
                  </div>
                ))}
              </div>
            </article>
          ))}
        </section>

        <CaseStudiesSection />
      </div>
      <Footer />
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Blog list page (PageBlog)
// ──────────────────────────────────────────────────────────────────────────
function PageBlog({ tag, author } = {}) {
  const isTag = !!tag;
  const isAuthor = !!author;
  const displayTag = isTag ? tag.toLowerCase() : "";
  const displayTagTitle = isTag ? tag.charAt(0).toUpperCase() + tag.slice(1) : "";

  const displayAuthorName = isAuthor
    ? author.split("-").map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(" ")
    : "";

  const meta = SITE_CONTENT.postsMeta || {};

  let pageTitle = meta.metaTitle;
  let pageDesc = meta.metaDescription;
  
  if (isTag) {
    pageTitle = `Articles in ${displayTagTitle} — Stories & Field Notes`;
    pageDesc = `Browse our latest articles, guides, and insights categorized under ${displayTagTitle}.`;
  } else if (isAuthor) {
    pageTitle = `Articles by ${displayAuthorName} — Stories & Field Notes`;
    pageDesc = `Read guides, thoughts, and technical essays written by ${displayAuthorName} at Border.`;
  }

  window.useSEO({
    title: pageTitle,
    description: pageDesc
  });

  let postsToRender = SITE_CONTENT.posts || [];
  if (isTag) {
    postsToRender = postsToRender.filter(p => (p.kind || "").toLowerCase() === displayTag);
  } else if (isAuthor) {
    postsToRender = postsToRender.filter(p => {
      const rawAuthors = (p.author || "").split(/,|\band\b|&/i).map(s => s.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "")).filter(Boolean);
      return rawAuthors.includes(author.toLowerCase());
    });
  }

  let crumbElement = "Blog";
  if (isTag) {
    crumbElement = <><a href="/blog" style={{ color: "inherit", textDecoration: "none" }}>Blog</a> / Tag</>;
  } else if (isAuthor) {
    crumbElement = <><a href="/blog" style={{ color: "inherit", textDecoration: "none" }}>Blog</a> / Author</>;
  }

  let h1Element = meta.title ? <span dangerouslySetInnerHTML={{ __html: meta.title }} /> : null;
  if (isTag) {
    h1Element = <>tag: <em>{displayTag};</em></>;
  } else if (isAuthor) {
    h1Element = <>author: <em>{author.toLowerCase()};</em></>;
  }

  let secTitleElement = (meta.sectionTitle || meta.secTitle) ? <span dangerouslySetInnerHTML={{ __html: meta.sectionTitle || meta.secTitle }} /> : null;
  if (isTag) {
    secTitleElement = null;
  } else if (isAuthor) {
    secTitleElement = null;
  }

  let authorCardElement = null;
  if (isAuthor) {
    const authorKey = author.toLowerCase();
    const authorInfo = (window.AUTHOR_INFO && window.AUTHOR_INFO[authorKey]);
    if (authorInfo) {
      authorCardElement = (
        <div className="art-author-card-page">
          <img src={authorInfo.avatar} className="art-sig-avatar" alt={authorInfo.name} style={{ width: 160, height: 160, borderRadius: '50%' }} />
          <div className="art-author-meta">
            <h2>{authorInfo.name}</h2>
            <p>{authorInfo.bio}</p>
          </div>
        </div>
      );
    }
  }

  return (
    <div className="bx-page site-page">
            <Nav />
      <div className="sp-frame">
        <PageHero
          h1={h1Element}
        />

        {authorCardElement}

        <section className="sp-section">
          {secTitleElement && (
            <div className="sp-section-head">
              <h2>{secTitleElement}</h2>
            </div>
          )}
          <div className="post-grid">
            {postsToRender.map((p, i) => {
              const cat = (p.kind || "").toLowerCase();
              const catClass = ["design", "culture", "dev", "art", "rip", "w3w"].includes(cat) ? `cat-${cat}` : "cat-default";
              return (
                <article key={p.title} className={`post-card ${catClass} ${(i === 0 && !isAuthor && !isTag) ? "featured" : ""}`}>
                  {p.image && (
                    <a href={`/blog/${p.slug}`} className="post-card-img-link">
                      <div className="post-card-img-wrap">
                        <img src={p.image} className="post-card-img" alt={p.title} />
                      </div>
                    </a>
                  )}
                  <div className="row">
                    <span>{p.date}</span>
                    <a href={`/blog/tag/${cat}`} className="kind">{p.kind}</a>
                  </div>
                  <h3>
                    <a href={`/blog/${p.slug}`} className="post-title-link">
                      {p.title}
                    </a>
                  </h3>
                  <div className="post-body">
                    <p>{p.excerpt}</p>
                    <a className="read" href={`/blog/${p.slug}`}>{p.read} · Read →</a>
                  </div>
                </article>
              );
            })}
          </div>
        </section>
      </div>
      <Footer />
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Contact
// ──────────────────────────────────────────────────────────────────────────
function PageContact() {
  const meta = SITE_CONTENT.contactMeta || {};

  window.useSEO({
    title: meta.metaTitle || meta.seoTitle || "",
    description: meta.metaDescription || meta.seoDesc || ""
  });
  const [status, setStatus] = React.useState('idle'); // 'idle' | 'submitting' | 'success' | 'error'
  const [errorMessage, setErrorMessage] = React.useState('');
  const [formInputs, setFormInputs] = React.useState({
    name: '',
    company: '',
    email: '',
    message: ''
  });

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormInputs(prev => ({ ...prev, [name]: value }));
  };

  const isFormValid = formInputs.name.trim() !== '' && 
                      /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formInputs.email) && 
                      formInputs.message.trim() !== '';

  const handleSubmit = (e) => {
    e.preventDefault();

    const accessKey = meta.web3formsAccessKey;
    if (!accessKey || accessKey === 'YOUR_ACCESS_KEY_HERE') {
      setStatus('error');
      setErrorMessage("Please configure your Web3Forms Access Key in content/contact.md first.");
      return;
    }

    setStatus('submitting');
    setErrorMessage('');

    const payload = {
      access_key: accessKey,
      name: formInputs.name,
      company: formInputs.company || 'N/A',
      email: formInputs.email,
      message: formInputs.message,
      subject: `New contact submission from ${formInputs.name}`
    };

    fetch('https://api.web3forms.com/submit', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify(payload)
    })
      .then(res => {
        if (!res.ok) throw new Error("Could not submit the form to Web3Forms");
        return res.json();
      })
      .then(data => {
        if (data.success) {
          setStatus('success');
          setFormInputs({ name: '', company: '', email: '', message: '' });
        } else {
          throw new Error(data.message || "Form submission failed");
        }
      })
      .catch(err => {
        console.error("Web3Forms submission error:", err);
        setStatus('error');
        setErrorMessage(err.message || "An error occurred while sending your message. Please try again.");
      });
  };

  return (
    <div className="bx-page site-page">
            <Nav />
      <div className="sp-frame">
        <PageHero
          h1={(meta.title || meta.introTitle) ? <span dangerouslySetInnerHTML={{ __html: meta.title || meta.introTitle }} /> : <>Tell us what you're <em>trying to ship.</em></>}
        />

        <section className="sp-section">
          <div className="contact-wrap">
            {status === 'success' ? (
              <div className="contact-success-wrap">
                <div className="success-icon">
                  <svg width="32" height="32" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <rect x="2" y="2" width="20" height="20" rx="6" fill="var(--ink)" />
                    <path d="M8 12L11 15L16 9" stroke="var(--paper)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                </div>
                <h3>Message sent successfully!</h3>
                <p>We've received your request. Our team will review the details and get back to you within a week.</p>
                <button className="reset-btn" onClick={() => setStatus('idle')}>Send another message</button>
              </div>
            ) : (
              <form className="contact-form" onSubmit={handleSubmit}>
                {[
                  { id: "name", label: "Your name" },
                  { id: "company", label: "Company", required: false },
                  { id: "email", label: "Work email", inputType: "email" },
                ].map(f => (
                  <label key={f.id}>
                    <span>{f.label}</span>
                    <input 
                      name={f.id} 
                      type={f.inputType || "text"} 
                      required={f.required !== false} 
                      disabled={status === 'submitting'}
                      value={formInputs[f.id]}
                      onChange={handleInputChange}
                    />
                  </label>
                ))}
                <label>
                  <span>What's the work?</span>
                  <textarea 
                    name="message" 
                    required 
                    rows={5} 
                    placeholder="What you're trying to ship, when, and why it matters." 
                    disabled={status === 'submitting'}
                    value={formInputs.message}
                    onChange={handleInputChange}
                  />
                </label>

                {errorMessage && (
                  <div className="contact-error-msg">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path d="M12 8V12M12 16H12.01M22 12C22 17.5228 17.5228 22 12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12Z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                    </svg>
                    <span>{errorMessage}</span>
                  </div>
                )}

                <button type="submit" aria-label="Send message" disabled={status === 'submitting' || !isFormValid}>
                  {status === 'submitting' ? (
                    <>
                      <span className="spinner" style={{ marginRight: 6 }} />
                      <span>Sending...</span>
                    </>
                  ) : (
                    <span>Send it →</span>
                  )}
                </button>
              </form>
            )}

            <aside className="contact-side">
              <div className="scard" style={{ backgroundColor: "var(--tile-cream-2)" }}>
                <div className="lbl">Direct</div>
                <a href={`mailto:${meta.emails?.[0]?.address || 'hi@borderux.com'}`} style={{ display: "block", marginBottom: 4 }}>
                  {meta.emails?.[0]?.address || 'hi@borderux.com'}
                </a>
                <a href={`tel:${(meta.phone || '+16193433779').replace(/[^0-9+]/g, '')}`} style={{ display: "block" }}>
                  {meta.phone || '+1 (619) 343-3779'}
                </a>
              </div>
              <div className="scard" style={{
                backgroundColor: "var(--tile-cream-3)",
                color: "var(--bx-light-tile-fg, var(--ink))"
              }}>
                <div className="lbl" style={{ color: "var(--bx-light-tile-fg-muted, var(--ink-2))" }}>
                  {meta.studio?.label || 'Studio'}
                </div>
                <a href={meta.studio?.mapUrl || "https://maps.app.goo.gl/9YBdDcfdxykQt8Sw8"} target="_blank" rel="noopener noreferrer" style={{ display: "block", color: "inherit" }}>
                  {meta.studio?.address ? (
                    meta.studio.address.split('\n').filter(Boolean).map((line, idx) => (
                      <React.Fragment key={idx}>
                        {line.trim()}
                        {idx < meta.studio.address.split('\n').filter(Boolean).length - 1 && <br />}
                      </React.Fragment>
                    ))
                  ) : (
                    <>401 W A St Suite 200<br />San Diego, CA 92101</>
                  )}
                </a>
              </div>
            </aside>
          </div>
        </section>
      </div>
      <Footer />
    </div>
  );
}

window.PageServices = PageServices;
window.PageOpenSource = PageOpenSource;
window.PageWork = PageWork;
window.PageBlog = PageBlog;
window.PageContact = PageContact;

// ─────────────────────────────────────────────────────────────────
// About
// ─────────────────────────────────────────────────────────────────
function PageAbout() {
  const meta = SITE_CONTENT.aboutMeta || {};

  window.useSEO({
    title: meta.metaTitle || meta.seoTitle || "",
    description: meta.metaDescription || meta.seoDesc || ""
  });

  const pillars = meta.pillars || [];
  const values = meta.values || [];

  const tones = ["t-cream-1", "t-cream-2", "t-cream-3"];
  return (
    <div className="bx-page site-page">
            <Nav />
      <div className="sp-frame">
        <PageHero h1={meta.title ? <span dangerouslySetInnerHTML={{ __html: meta.title }} /> : ""} />
        
        <section className="sp-section pt-0 pb-0" style={{ marginTop: "calc(var(--tile-gap) * 1.5)" }}>
          <div className="sp-section-head" style={{ borderTop: "none" }}>
            <h2>How we <em>work.</em></h2>
          </div>
        </section>

        <div className="sp-bento-grid">
          {pillars.map((p, i) => (
            <article key={p.n} className={`sp-card ${tones[i % tones.length]}`}>
              <div className="sp-num">{p.n}</div>
              <h3>{p.title}</h3>
              <div className="sp-body">
                <p dangerouslySetInnerHTML={{ __html: p.body }} />
              </div>
            </article>
          ))}
        </div>

        <section className="sp-section" style={{ marginTop: "calc(var(--tile-gap) * 3.5)" }}>
          <div className="sp-section-head">
            <h2 dangerouslySetInnerHTML={{ __html: meta.teamTitle || "Meet our <em>team.</em>" }} />
          </div>
          <div className="team-row" style={{ display: 'flex', gap: '24px', flexWrap: 'wrap', justifyContent: 'center' }}>
            {Object.entries(window.AUTHOR_INFO || {}).map(([slug, auth]) => (
              <div key={slug} className="art-author-card-page" style={{ margin: '0', flex: '1 1 280px', minWidth: '260px' }}>
                <img src={auth.avatar} className="art-sig-avatar" alt={auth.name} style={{ width: '160px', height: '160px', borderRadius: '50%' }} />
                <div className="art-author-meta">
                  <h2>{auth.name}</h2>
                  <p>{auth.bio}</p>
                </div>
              </div>
            ))}
          </div>
        </section>

        <section className="sp-section pt-0 pb-0" style={{ marginTop: "calc(var(--tile-gap) * 3.5)" }}>
          <div className="sp-section-head" style={{ borderTop: "none" }}>
            <h2>What we <em>value.</em></h2>
          </div>
        </section>

        {values.length > 0 && (
          <div className="sp-values-grid" style={{ marginBottom: "var(--tile-gap)" }}>
            {values.map((v, i) => (
              <article key={v.n} className={`sp-card sp-value-card-${i + 1}`} style={{ minHeight: "350px", padding: "40px", display: "flex", alignItems: "center", justifyContent: "center" }}>
                <h3 
                  style={{ fontSize: "clamp(30px, 4.9vw, 81px)", lineHeight: "1.12", fontWeight: "450", letterSpacing: "-0.01em", textAlign: "center", margin: 0 }}
                  dangerouslySetInnerHTML={{ __html: v.body }}
                />
              </article>
            ))}
          </div>
        )}
      </div>
      <Footer />
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────
// Careers
// ─────────────────────────────────────────────────────────────────
function PageCareers() {
  const meta = SITE_CONTENT.careersMeta || {};

  window.useSEO({
    title: meta.metaTitle || meta.seoTitle || "",
    description: meta.metaDescription || meta.seoDesc || ""
  });

  const perks = meta.perks || [];

  const openPositions = meta.openPositions || {};

  const tones = ["t-cream-1", "t-cream-2", "t-cream-3"];
  return (
    <div className="bx-page site-page">
            <Nav />
      <div className="sp-frame">
        <PageHero h1={meta.title ? <span dangerouslySetInnerHTML={{ __html: meta.title }} /> : ""} />
        <div className="sp-bento-grid">
          {perks.map((p, i) => (
            <article key={p.n} className={`sp-card ${tones[i % tones.length]}`}>
              <div className="sp-num">{p.n}</div>
              <h3>{p.title}</h3>
              <div className="sp-body">
                <p dangerouslySetInnerHTML={{ __html: p.body }} />
              </div>
            </article>
          ))}
        </div>

        <section className="sp-case-study cs-dark" id="careers-open">
          <div className="sp-case-head">
            <div className="lbl">{openPositions.title}</div>
          </div>
          <div className="sp-case-body">
            <div className="sp-case-text">
              <h2 dangerouslySetInnerHTML={{ __html: openPositions.heading }} />
              <p dangerouslySetInnerHTML={{ __html: openPositions.body }} />
            </div>
          </div>
        </section>
      </div>
      <Footer />
    </div>
  );
}

function Page404({ message }) {
  window.useSEO({
    title: "404 Page Not Found | Border UX",
    description: "It looks like the layout constraints on this page have collapsed. Rebuild it with us."
  });

  // Generate 80 stable background drifting starry confetti particles
  const particles = React.useMemo(() => {
    const list = [];
    const colors = ['#F2D24A', '#FBDBB3', '#4F5BE7', '#B42D45', '#F4ECD8', '#2D94B4', '#A2C2E8'];
    const shapes = ['circle', 'square', 'diamond', 'triangle', 'star'];
    for (let i = 0; i < 80; i++) {
      const size = Math.floor(Math.random() * 6) + 3; // 3px to 8px
      const x = Math.random() * 100; // 0% to 100%
      const y = Math.random() * 100; // 0% to 100%
      const color = colors[i % colors.length];
      const shape = shapes[i % shapes.length];
      
      const driftX = (Math.random() - 0.5) * 50; // -25px to 25px
      const driftY = (Math.random() - 0.5) * 50; // -25px to 25px
      const driftSpeed = 8 + Math.random() * 12; // 8s to 20s
      const tilt = -45 + Math.random() * 90; // -45deg to 45deg
      
      list.push({
        id: i,
        x,
        y,
        size,
        color,
        shape,
        driftX,
        driftY,
        driftSpeed,
        tilt
      });
    }
    return list;
  }, []);

  return (
    <div className="bx-page site-page" style={{ position: 'relative', overflow: 'hidden', minHeight: '100vh' }}>
            <Nav />
      
      {/* Drifting background stars */}
      <div className="stars-bg">
        {particles.map((p) => (
          <div 
            key={p.id} 
            className={`confetti shape-${p.shape}`} 
            style={{
              left: `${p.x}%`,
              top: `${p.y}%`,
              width: `${p.size}px`,
              height: `${p.size}px`,
              backgroundColor: p.color,
              color: p.color,
              '--size': `${p.size}px`,
              '--drift-x': `${p.driftX}px`,
              '--drift-y': `${p.driftY}px`,
              '--drift-speed': `${p.driftSpeed}s`,
              '--tilt': `${p.tilt}deg`,
            }}
          />
        ))}
      </div>

      <div className="sp-frame" style={{ position: 'relative', zIndex: 2 }}>
        <section className="err-hero">
          <h1 className="err-title">Lost in space.</h1>
          <div className="err-subtitle">{message || "HTTP 404"}</div>
          <div style={{ display: 'flex', justifyContent: 'center', marginTop: '40px' }}>
            <a href="/" className="err-btn primary">← Back Home</a>
          </div>
        </section>
      </div>
      <Footer />
    </div>
  );
}

window.PageAbout = PageAbout;
window.PageCareers = PageCareers;
window.Page404 = Page404;