// Trellum — App shell, URL routing, runtime metadata sync

const { useState, useEffect, useRef } = React;

// Reverse of PAGE_PATHS (defined in Primitives.jsx)
const PATH_TO_PAGE = Object.fromEntries(
  Object.entries(PAGE_PATHS).map(([page, path]) => [path, page])
);

const SITE_ORIGIN = 'https://trellum.co.uk';

// Per-page <head> metadata. Each per-route HTML file (services/index.html,
// pfi/index.html, ...) ships with these values pre-baked for the crawler;
// when a user navigates client-side we sync them at runtime so the URL,
// title, canonical and og:url stay correct.
const PAGE_META = {
  home: {
    title: 'Trellum — Built Environment Advisory · PFI, BSA & FM AI',
    description: "Trellum is a UK practitioner advisory for organisations carrying complex built environment obligations. Payment Mechanism Audits for PFI contracts, BSA golden-thread evidence for higher-risk residential buildings, and AI tooling built into FM workflows.",
    ogTitle: 'Trellum — Built Environment Advisory',
    ogDescription: 'UK practitioner advisory for PFI payment mechanisms, BSA golden-thread evidence, and AI tooling built into FM workflows. Contract literacy. Operational depth. Tools the team can keep.',
  },
  services: {
    title: 'Services — Fixed-Fee FM Engagements · Trellum',
    description: 'Trellum services: Digital Readiness Assessment, FM AI Engineering, FM Digital Adoption, Contract & Compliance Intelligence. Fixed-fee, scoped, and built so the team can maintain the output.',
    ogTitle: 'Services — Trellum',
    ogDescription: 'Fixed-fee engagements. Defined scope. Deployable outputs. Digital Readiness Assessment, FM AI Engineering, Digital Adoption, Contract & Compliance Intelligence.',
  },
  pfi: {
    title: 'PFI Payment Mechanism Audit · Trellum',
    description: "A four-week, fixed-fee Payment Mechanism Audit for UK PFI contracts. The schedule read against the authority's recorded service events, returning a register of where contractual deduction entitlement and reported position diverge.",
    ogTitle: 'PFI Payment Mechanism Audit — Trellum',
    ogDescription: "653 live UK PFI contracts. The audit reads the PM schedule against the authority's recorded service events and returns a register of deduction entitlement vs reported position.",
  },
  block: {
    title: 'BSA Golden Thread Gap Audit · Trellum',
    description: 'A fixed-fee Golden Thread Gap Audit for managing agents, RMCs, RTMs, and Accountable Persons. BSA Part 4 information requirements read against the records the organisation holds, returned as an audit-ready register.',
    ogTitle: 'BSA Golden Thread Gap Audit — Trellum',
    ogDescription: 'Building Safety Act golden-thread evidence the Accountable Person can defend at a safety-case review. Fixed-fee, audit-ready register. For managing agents, RMCs, RTMs, and named APs.',
  },
  approach: {
    title: 'Approach · Trellum Built Environment Advisory',
    description: 'Trellum is a practitioner advisory built on four compounding layers: commercial, technical, contractual, digital. A full-lifecycle view of the built environment from transaction to digital operation.',
    ogTitle: 'Approach — Trellum',
    ogDescription: 'Practitioner advisory for organisations inside the built environment, not consulting to it. Four compounding layers: commercial, technical, contractual, digital.',
  },
  contact: {
    title: 'Contact · Trellum',
    description: 'Contact Trellum about a PFI Payment Mechanism Audit, a BSA Golden Thread Gap Audit, or an FM AI engagement. Reply within two working days. UK business hours. No autoresponders.',
    ogTitle: 'Contact — Trellum',
    ogDescription: "Tell us what you're carrying. We reply within two working days. UK business hours. No autoresponders. hello@trellum.co.uk.",
  },
};

const pathToPage = (path) => {
  const clean = path.replace(/\/+$/, '') || '/';
  return PATH_TO_PAGE[clean] || 'home';
};

const setMetaContent = (selector, content) => {
  const el = document.head.querySelector(selector);
  if (el) el.setAttribute('content', content);
};
const setLinkHref = (selector, href) => {
  const el = document.head.querySelector(selector);
  if (el) el.setAttribute('href', href);
};

const syncMetadata = (page) => {
  const meta = PAGE_META[page];
  if (!meta) return;
  document.title = meta.title;
  setMetaContent('meta[name="description"]', meta.description);
  setMetaContent('meta[property="og:title"]', meta.ogTitle);
  setMetaContent('meta[property="og:description"]', meta.ogDescription);
  setMetaContent('meta[name="twitter:title"]', meta.ogTitle);
  setMetaContent('meta[name="twitter:description"]', meta.ogDescription);
  const url = SITE_ORIGIN + (PAGE_PATHS[page] || '/');
  setMetaContent('meta[property="og:url"]', url);
  setLinkHref('link[rel="canonical"]', url);
};

const App = () => {
  const [page, setPage] = useState(() => pathToPage(window.location.pathname));
  const h1Ref = useRef(null);

  const go = (p) => {
    const target = PAGE_PATHS[p] || '/';
    const current = window.location.pathname.replace(/\/+$/, '') || '/';
    if (current !== target) {
      window.history.pushState({ page: p }, '', target);
    }
    setPage(p);
    window.scrollTo({ top: 0, behavior: 'auto' });
  };

  useEffect(() => {
    syncMetadata(page);
    const t = setTimeout(() => {
      if (h1Ref.current) {
        try { h1Ref.current.focus({ preventScroll: true }); } catch (e) {}
      }
    }, 50);
    return () => clearTimeout(t);
  }, [page]);

  useEffect(() => {
    const onPop = () => setPage(pathToPage(window.location.pathname));
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  return (
    <>
      <Nav page={page} setPage={go} />
      {page === 'home' && <Home setPage={go} h1Ref={h1Ref} />}
      {page === 'services' && <Services setPage={go} h1Ref={h1Ref} />}
      {page === 'pfi' && <PFI setPage={go} h1Ref={h1Ref} />}
      {page === 'block' && <Block setPage={go} h1Ref={h1Ref} />}
      {page === 'approach' && <Approach setPage={go} h1Ref={h1Ref} />}
      {page === 'contact' && <Contact setPage={go} h1Ref={h1Ref} />}
      <Footer setPage={go} />
    </>
  );
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
